LoginSignup
0

More than 3 years have passed since last update.

【JavaScript】非同期処理の書き方 async/await編

Last updated at Posted at 2020-11-21

【JavaScript】非同期処理の書き方 Promise編に引き続き、JavaScriptでの非同期処理について書きます。
今回はPromiseをより簡潔に書けるようにES2017で導入されたasync/awaitについて書きます

asyncとは何か?

非同期関数を定義する関数定義です。
async function で非同期関数を定義できます。
async function は Promise インスタンスを返却します。

async function sample(){
return 'Hello World!!';
}

上記の例で定義した sample は、Promiseで書くと以下の様になります。


function sample() {
  return new Promise((resolve, reject) => {
    resolve('Hello World!!');
  });
}

asyncの利用例

async function で定義された関数内でreturnされると、そのreturnの返り値で Promise.resolveもしくはreject が実行される為、.then()や.catch()でreturnの値を受け取ることができます。


async function resolveSample() {
          return "sample was resolved!";
        }
        async function rejectSample() {
          // reject を呼ぶ
          return Promise.reject(new Error("エラーです..."));
        }
        async function throwSample() {
          throw new Error("エラーが発生");
        }

        resolveSample().then((value) => {
          console.log(value); 
        });
        // 実行結果 =>sample was resolved!

        rejectSample().catch((error) => {
          console.log(error.message);
        });
        // 実行結果 => エラーです...

        // catch() で例外処理を行える
        throwSample().catch((error) => {
          console.log(error.message);
        }); // => エラーが発生

awaitとは何か?

async function内でPromiseの結果(resolve、reject)が返されるまで処理を一時停止する演算子のことです。awaitはasync function で利用することが出来ます。

async/awaitを使って非同期処理を書く

【JavaScript】非同期処理の書き方 Promise編で書いた以下の処理を実際にasync/awaitを使って書いていきます。
Screen Recording 2020-11-15 at 10.23.33.mov.gif

以下は前回↑の処理をasync/awaitを使わないで書いた処理です。

///(async/awaitを使わない処理)
            const getRelated = publisher =>{
                return new Promise((resolve, reject) =>{
                    setTimeout(pub =>{
                        const recipe = { title: 'Ramen', publisher: 'Tony' }
                        resolve(`${pub}: ${recipe.title}`);
                    }, 2000, publisher);
                });
            };

            const getIDs = new Promise((resolve, reject) =>{
                setTimeout(() =>{
                    resolve([523, 883, 473, 974]);
                }, 1500);
            });

            const getRecipe = recId =>{
                return new Promise((resolve, reject) =>{
                    setTimeout(ID =>{
                        const recipe = { title: 'Udon', publisher: 'Taro' };
                        resolve(`${ID}: ${recipe.title}`)
                    }, 2000, recId);
                });
            };

            getIDs
            .then(IDs => {
                console.log(IDs);
                return getRecipe(IDs[2]);
            })
            .then(recipe => {
                console.log(recipe);
                return getRelated('Tony');
            })
            .then(recipe => {
                console.log(recipe);
            })

次はasync/awaitを使って書いた処理です。

///(async/awaitを使った処理)
        const getRelated = (publisher) => {
          return new Promise((resolve, reject) => {
            setTimeout(
              (pub) => {
                const recipe = { title: "Ramen", publisher: "Tony" };
                resolve(`${pub}: ${recipe.title}`);
              },
              2000,
              publisher
            );
          });
        };

        const getIDs = new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve([523, 883, 473, 974]);
          }, 1500);
        });

        const getRecipe = (recID) => {
          return new Promise((resolve, reject) => {
            setTimeout(
              (IDs) => {
                const recipe = { title: "Udon", publisher: "Taro" };
                resolve(`${IDs}: ${recipe.title}`);
              },
              2000,
              recID
            );
          });
        };
async function getRecipesAW() {
          const IDs = await getIDs;
          console.log(IDs);
          const recipe = await getRecipe(IDs[2]);
          console.log(recipe);
          const related = await getRelated("Tony");
          console.log(related);

          return recipe;
        }
        getRecipesAW();

async/awaitを使うことでコードを簡潔に書くことが出来ます。

参考

MDN web docs 非同期関数

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0