async/awaitは、非同期処理をよりシンプルに記述することができます。
関連ページ
Promiseによる非同期処理[resolve][reject][Promise.all]
下記コードを実行すると、2秒後に「範囲内」と表示されます。16行目のtestFunction(10)の引数を仮に1000にすると「エラーです。範囲外」と表示されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function testFunction(value) { return new Promise(function (resoleve, reject) { setTimeout(function () { let n = value; if (n < 100) { resoleve("範囲内"); } else { reject("範囲外"); } }, 2000); }) } async function myAsync(){ try{ let result = await testFunction(10); console.log(result); }catch(error){ console.log(`エラーです。${error}`); } } myAsync(); |
14行目
asyncを付けると、その関数はPromiseを返すようになります。
16行目
awaitはPromiseの値が返ってくるまで待ってくれます。awaitはasyncを付けた関数の中でのみ利用できます。
仮に引数を1000にして処理が失敗した場合、すなわちreject関数が実行された場合は例外として処理され、19行目の処理にてエラーが表示されます。
非同期処理の連結
下記コードを実行すると、2秒ごとに「範囲内」→「範囲内」→「エラーです。範囲外」と順番に表示されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
function testFunction(value) { return new Promise(function (resoleve, reject) { setTimeout(function () { let n = value; if (n < 100) { resoleve("範囲内"); } else { reject("範囲外"); } }, 2000); }) } async function myAsync() { try { console.log(await testFunction(10)); console.log(await testFunction(50)); console.log(await testFunction(900)); } catch (error) { console.log(`エラーです。${error}`); } } myAsync(); |
複数の非同期処理を並列処理で実行
複数の非同期処理を並列処理で一気に実行することもできます。下記を実行すると、2秒後に「[ ‘範囲内’, ‘範囲内’, ‘範囲内’ ]」と表示されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
function testFunction(value) { return new Promise(function (resoleve, reject) { setTimeout(function () { let n = value; if (n < 100) { resoleve("範囲内"); } else { reject("範囲外"); } }, 2000); }) } async function myAsync() { try { let result = await Promise.all([ testFunction(10), testFunction(50), testFunction(90) ]); console.log(result); } catch (error) { console.log(`エラーです。${error}`); } } myAsync(); |
Promise.all関数によって3つのtestFunction関数を並列に処理しています。もしtestFunction(1000)のようなrejectを呼び出す処理が一つでも存在すると、例外処理されエラーが表示されます。