今の今まで間違った認識でいた、やばぁ.asyncとawaitとPromise

2024.08.20

Logging

おはようございます.今の今まで間違った認識でいた、やばぁ.asyncとawaitとPromiseの関係.asyncは非同期、awaitは同期(処理待ち)だと思う.ここでasyncした関数を取得するにはawaitして取得するだけで良いみたい.そうPromiseは出番なくて良いみたい😱.

例文コードを書いていきます.まずは非同期処理の場合です.

async function example1(a){
    if(Number.isInteger(a)){
        return a;
    }
    throw new Error('wow');
}

example1(123).then(d=>console.log(d)).catch(e=>console.log(e));
example1('abc').then(d=>console.log(d)).catch(e=>console.log(e));

こんな感じに書けば良いだけ....

次に処理待ちの場合はこんな感じです.

async function example2(a){
    if(Number.isInteger(a)){
        return a;
    }
    throw new Error('wow');
}
async function example3() {
    let result = await example2(123).then(d=>d);
    document.body.textContent = result;
}
example3();

async function example4() {
    let result = await example2('123').then(d=>d).catch(e=>e);
    document.body.textContent = result;
}
//example4();

非常にシンプルなコードです.こんな感じで取得することが出来るからPromiseを使ったコードを見なくなったのですね😁.

もっと詳しく知りたい方は下記の記事を参考にしてみてください.

https://qiita.com/soarflat/items/1a9613e023200bbebcb3

明日へ続く.

著者名  @taoka_toshiaki

Profile
高知県在住の@taoka_toshiakiです、記事を読んで頂きありがとうございます.
数十年前から息を吸うように日々記事を書いてます.たまに休んだりする日もありますがほぼ毎日投稿を心掛けています😅.
SNSも使っています、フォロー、いいね、シェア宜しくお願い致します🙇.
SNS::@taoka_toshiaki

タグ

async function example, asyncとawait, await, await example, body.textContent, catch, console.log, example, example1, example3, example4, if, let result, Number.isInteger, Promise, result, then, 出番, 同期, 関数,