promise的瞭解

promise的瞭解

  • 依照 Promise/A+ 的定義,Promise 有四種狀態:
    • pending: 初始狀態, 非 fulfilledrejected.
    • fulfilled: 成功的操作.
    • rejected: 失敗的操作.
    • settled: Promise已被fulfilledrejected,且不是pending
  • 另外, fulfilledrejected一起合稱 settled
  • Promise 對象用來進行延遲(deferred) 和異步(asynchronous) 計算

Promise 的構造函數

  • 構造一個 Promise,最基本的用法如下:
var promise = new Promise(function(resolve, reject) {

        if (...) {  // succeed

            resolve(result);

        } else {   // fails

            reject(Error(errMessage));

        }
    });
  • Promise 實例擁有 then 方法(具有 then 方法的對象,通常被稱爲thenable)。它的使用方法如下:
promise.then(onFulfilled, onRejected)
  • 接收兩個函數作爲參數,一個在 fulfilled 的時候被調用,一個在rejected的時候被調用,接收參數就是 futureonFulfilled 對應resolve, onRejected對應 reject

個人博客地址:大家可以看看

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章