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

20240820

文字数[1074文字] この記事は1分21秒で読めます.

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

明日へ続く.




3114番目の投稿です/408 回表示されています.

中の人🏠️

AIによるおすすめ記事

著者名  @taoka_toshiaki

※この記事は著者が40代前半に書いたものです.

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

OFUSEで応援を送る

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA


タグ

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, 出番, 同期, 関数,