LoginSignup
0
0

More than 1 year has passed since last update.

async/awaitを一言で説明する

Last updated at Posted at 2022-07-29

丁寧な説明は多いが結局なんだっけ?となったので一言にしてみた。
要するにasync/awaitとは、

asyncの中でawaitを使うと、promiseが返ってくるまで待ってくれる仕組みのこと

test.js
async function test(){
    console.log('1');
    await setTimeout(() => {console.log('2 (非同期処理)')}, 1000);
    console.log('3');
};

出力結果

1
2 (非同期処理) // awaitしたので非同期処理でも記述順に実行される。
3

// awaitしないと132となる。

ということは、awaitを使いたくなったら最後にpromiseを返せばOK

testPromise.js
function testPromise(){
    return new Promise(function(resolve){
            // 何らかの非同期を含む処理
            // ・・・・・・・・・・・
            resolve('2 (testPromise)');        
        }).then(function(result){
            return result;
        });
}

(async ()=>{
    console.log('1');
    console.log(await testPromise());
    console.log('3');
})();

戻り値

1
2 (testPromise)
3

慣れるとどんどん入れ子になっていきます。
~ 完 ~

0
0
2

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
0