[JavaScript]Async/Awaitのクリーンアップ
19588 ワード
使用( getData関数はpromise(上記のように) を返します.thenを使用して結果を受信できます. では、Async/Awaitを使用して、上記の
上のコードはPromiseチェーンコードと同じ動作です.
request()の場合、async関数ではtry catch構文を使用して次のように処理されます.
では、Promiseセクションの3つのTaskを連続的に処理してみましょう.
各タスクプロセスの定義は次のとおりです.
まず,Promiseチェーンを用いて実装したコードを以下に示す.
結果
以上の比較から、Async Awaitの使用はPromise Chaningの使用よりも毒性が高いことが分かる.
Async関数内で同時に複数のプロセスを実行するために、
Promise.allメソッドを使用できます.
結果
Async / Await
は使用Promise chaining
よりも毒性がある.Async
は関数の前のキーワードAwait
は、Promiseオブジェクトの前のキーワードです.Await
キーワードはAsync
関数でのみ使用可能)使用例
function getData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('data~');
}, 1500)
});
}
// Promise chaining version.
getData()
.then((res) => console.log(res))
then
メソッドと同じ動作を作成します.// Async Await version.
async function printData() {
const data = await getData();
console.log(data);
}
printData();
上のコードはPromiseチェーンコードと同じ動作です.
request()の場合、async関数ではtry catch構文を使用して次のように処理されます.
async function printData() {
try {
const data = await getData();
console.log(data);
} catch(err) {
console.log(err);
}
}
printData();
質問する
では、Promiseセクションの3つのTaskを連続的に処理してみましょう.
各タスクプロセスの定義は次のとおりです.
const task1 = () => {
console.log('Task 1 is started.')
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Task 1 is done.');
resolve(1);
}, 2000);
})
};
const task2 = () => {
console.log('Task 2 is started.')
return new Promise((resolve, reject) => {
setTimeout(() => {
// reject('오류메시지');
console.log('Task 2 is done.');
resolve(2);
}, 500);
})
};
const task3 = () => {
console.log('Task 3 is started.')
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Task 3 is done.');
resolve(3);
}, 1000);
})
};
Promiseチェーンバージョン
まず,Promiseチェーンを用いて実装したコードを以下に示す.
/* Promise chaining version. */
task1()
.then(() => task2())
.then(() => task3())
.then(() => console.log('Completed!'))
.catch(console.log)
.finally(() => console.log('Done.'));
Async Awaitバージョン
/* Async Await version */
async function doTasks() {
try {
const data1 = await task1();
const data2 = await task2();
const data3 = await task3();
console.log(data1, data2, data3);
} catch(err) {
console.log(err);
}
console.log('Done.');
}
doTasks();
結果
Promise.all
Async関数内で同時に複数のプロセスを実行するために、
Promise.allメソッドを使用できます.
async function doTasks() {
try {
const data = await Promise.all([task1(), task2(), task3()]);
console.log(...data);
} catch(err) {
console.log(err);
}
console.log('Done.');
}
doTasks();
結果
Reference
この問題について([JavaScript]Async/Awaitのクリーンアップ), 我々は、より多くの情報をここで見つけました https://velog.io/@hyeonseop/JavaScript-Async-Await-정리テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol