🌟

Promiseとasync/awaitの違い

2021/06/24に公開

検証

下記3パターンで違いを検証

  1. Promise関数を使うPromise関数(catchあり)を実行
  2. Promise関数を使うPromise関数(catchなし)を実行
  3. Promise関数を使うasync関数を実行

結論

  1. 例外補足できる
  2. 例外補足できない
  3. 例外補足できる

それぞれのコード&結果の例

1. Promise関数を使うPromise関数(catchあり)を実行

300ミリ秒以上の時間を待つプログラム。300ミリ秒未満の場合は例外発生

sample1.js
function waitSec (time, callback) { 
    return new Promise(function(resolve, reject) {
        if (time >= 3) {
            setTimeout(() => {callback(time + '00 ms have passed.'); resolve('wait sec');}, time * 100)
        } else {
            reject('wait sec error');    
        }
    });
}

function wrapWaitSec (time) {
    return new Promise(function(resolve, reject) {
        waitSec(time, (res) => resolve(res)).catch(err => reject(err))
    });
}

// ここのtimeを変更する
const time = 3

wrapWaitSec(time).then((res) => {
    console.log('OK: ' + res);
}).catch((err) => {
    console.log('ERROR: ' + err);
});

正常系

実行結果
OK: 300 ms have passed.

異常系

sample1.js
// ここのtimeを変更する
+ const time = 1
- const time = 3
実行結果
ERROR: wait sec error

2. Promise関数を使うPromise関数(catchなし)を実行

sample1.js
+ waitSec(time, (res) => resolve(res))
- waitSec(time, (res) => resolve(res)).catch(err => reject(err))

timeは初期設定のままにします。
const time = 3

正常系

実行結果
OK: 300 ms have passed.

異常系

sample1.js
// ここのtimeを変更する
+ const time = 1
- const time = 3
実行結果
UnhandledPromiseRejectionWarning: wait sec error

waitSec関数の例外が補足できていない警告が出てしまう

3. Promise関数を使うasync関数を実行

sample1.js
+ async function wrapWaitSec (time) {
+    let result = ''
+    await waitSec(time, (res) => { result = res })
+    return result
+ }
- function wrapWaitSec (time) {
-    return new Promise(function(resolve, reject) {
-        waitSec(time, (res) => resolve(res)).catch(err => reject(err))
-    });
- }

+ async function main () {
+    try {
+        // ここのtimeを変更する
+        const time = 3
+        const res = await wrapWaitSec(time);
+        console.log('OK: ' + res);
+    } catch (err) {
+        console.log('ERROR: ' + err);
+    }
+ }

+ main()

- // ここのtimeを変更する
- const time = 3

- wrapWaitSec(time).then((res) => {
-     console.log('OK: ' + res);
- }).catch((err) => {
-     console.log('ERROR: ' + err);
- });

正常系

実行結果
OK: 300 ms have passed.

異常系

sample1.js
// ここのtimeを変更する
+ const time = 1
- const time = 3
実行結果
ERROR: wait sec error

結論

  • 独自に作成したPromise関数内部で別のPromise関数を使用する場合は、必ず直後にcatchをつける。
  • 独自に作成したasync関数内部でPromise関数を使用する場合は、特に意識しなくてOK

感想

promiseとasyncでどっちを使った方がいいかは、好みなのかな、、?

TODO:先輩に教えてもらった、azuさんのPromise本を読む
https://azu.github.io/promises-book/

一緒に読みたい人募集中です〜〜〜

Discussion