非同期処理を順番に実行する
わかりやすいrmaruon.icon
code:js
(() => {
const sleep = (seconds) => new Promise(resolve => setTimeout(resolve, seconds * 1000));
(async () => {
await sleep(1);
console.log("1 end")
})();
// async/awaitによる順次処理
(async () => {
await sleep(2);
console.log("2 end")
await sleep(1);
console.log("2-1 end");
await sleep(1);
console.log("2-1-1 end");
await sleep(1);
console.log("2-1-1-1 end");
})();
})();
code:js
(() => {
const sleep = (seconds) => new Promise(resolve => setTimeout(resolve, seconds * 1000));
sleep(1).then(() => {
console.log("1 end")
});
sleep(2)
.then(() => {
console.log("2 end");
return sleep(1);
})
.then(async () => {
console.log("2-1 end");
await sleep(1);
})
.then(() => {
console.log("2-1-1 end");
})
.then(() => sleep(1))
.then(() => console.log("2-1-1-1 end"));
})();
Promiseチェーンを壊さないように注意する
then内のコールバックでPromiseを返さないと、非同期処理が順次処理されない(意図しない並行処理が発生する) JavaScriptの仕様上、間違いやすい
複数行を記述するときは注意する
code:js
// Promiseを返す
() => sleep(5);
() => { return sleep(5) };
// Promiseを返さない
() => { sleep(5) };
() => {
hoge();
sleep(5);
};
async/awaitで書けば、特に気にする必要はない
PromsiMDNによる「よくある間違い」がわかりやすいrmaruon.icon
他の2つも参考になる
then内でPromiseをreturnしたら、then自体がPromiseを返す
だから、thenはネストする必要ない
catchを書こう
.catch(error => console.log(error))