LoginSignup
1
0

More than 1 year has passed since last update.

【JavaScript】Promiseの書き方

Last updated at Posted at 2021-07-05

1.概要

久しぶりに JS を書いた際にPromiseの実装をすっかり忘れていたので備忘録として残しておきます。

外部のAPIを叩いてそのレスポンスを処理する という処理を想定しています。

2.実装

Promiseの使い方を忘れていたのでいろんなパターンを書いて実行してみました!
https://github.com/smoto-shei/Vue/blob/master/ProcessDemo/src/components/ProcessDemo.vue

↓一番わかりやすくて簡単だと思ったコードがこちらです。
fakeAPI()は外部のAPIをを叩くことを想定し、setTimeoutでレスポンスに1秒かかるようにしています。
buyApple5 はAPIのレスポンス結果を処理する関数を想定しています。

// OK 疑似的 API
fakeAPI(payment) {
    // プロミスを作る
    return new Promise(function(okFunc, ngFunc) {
    setTimeout(function() {
        if (payment >= 150) {
        okFunc(payment - 150);
        } else {
        ngFunc("金額がたりません");
        }
    }, 1000);
    });
},

// 8番目のボタン
async buyApple5() {
    // await は Promise の値が取り出されるまでまつ
    // 処理に失敗した場合(==ngFuncが帰って来た場合)は catch に入る
    const self = this;
    try {
    var status = await self.fakeAPI(1000);
    console.log("残りの金額は", status, "円です");
    } catch (error) {
    console.log(error);
    }
}

3.最後に

より良い実装があればご教授いただきたいです><
TypeScript を使えばもっと簡単にかけるのかしら

1
0
1

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
1
0