0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Promise (resolve) / (reject) について勉強

Posted at

Promise

Promiseの引数にresolverejectがあり、非同期処理が実行された場合のコールバック関数となります。

コールバック関数: **関数の引数には、関数が渡せる。これを利用して、「ある特定の処理が終わったら、引数に渡した関数の処理を実行する」といったように、処理のフローを制御することができる。
その際、
「終わったら実行したい処理」**をコールバック関数として渡します。
(非同期処理関数は処理が終わったらコールバック関数を呼び出す。)

resolveは処理が正常に終了した時に呼ばれるコールバック関数です。
また上記では記述されていませんが、rejectは処理が失敗した時に呼ばれるコールバック関数となります。

new Promise(callback)

Promiseを利用するにはPromiseをnewでインスタンスを作ります。

作ったインスタンスはそのままリターンさせて
実際の処理はCallbackを渡して書いていきます。

そして成功すればresolveを失敗すればrejectを呼び出します。

example.js

addCategories({ commit, rootgetters }, inputCategory){
      return new Promise((resolve) => { 
        axios(rootgetters['auth/token'])({
          method: 'POST',
          url: '/category',
        }).then(() => {
          commit('doneAddCategory');
        }).catch ((err) => {
          commit('failFetchCategory', { message: err.message });
        });
      });
    },

参考

今更だけどPromise入門
JavaScript中級者への道【5. コールバック関数】

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?