看完这个代码示例就明了了:
- 异步函数 - 提高 Promise 的易用性 | Web | Google Developers
- async/await 入門(JavaScript) - Qiita
- async, await入門 - Qiita
// Promise
const hoge = value => {
return new Promise(resolve => {
setTimeout(() => {
resolve(value * 2);
}, 1000);
})
}
const fuga = value => {
return new Promise(resolve => {
setTimeout(() => {
resolve(value * 3);
}, 500);
})
}
const promiseAllSample = () => {
const promise1 = hoge(5);
const promise2 = hoge(10);
const promise3 = promise2.then(value => {
return fuga(value);
});
return Promise.all([promise1, promise2, promise3]);
}
promiseAllSample().then(([a, b, c]) => {
console.log(a, b, c); // => 10 20 60
});
// Async/Await
const hoge = value => {
return new Promise(resolve => {
setTimeout(() => {
resolve(value * 2);
}, 1000);
})
}
const fuga = value => {
return new Promise(resolve => {
setTimeout(() => {
resolve(value * 3);
}, 500);
})
}
const promiseAllSample = async () => {
const [a, b] = await Promise.all([hoge(5), hoge(10)]);
const c = await fuga(b);
return [a, b, c];
}
promiseAllSample().then(([a, b, c]) => {
console.log(a, b, c); // => 10 20 60
});