js之promise講解

來源:互聯網
上載者:User

標籤:情況   示範   簡化   failure   ima   cas   turn   預設   結果   

1 Promise概述

Promise對象是CommonJS工作群組提出的一種規範,目的是為非同步作業提供統一介面。

那麼,什麼是Promises?

首先,它是一個對象,也就是說與其他JavaScript對象的用法,沒有什麼兩樣;其次,它起到代理作用(proxy),充當非同步作業與回呼函數之間的中介。它使得非同步作業具備同步操作的介面,使得程式具備正常的同步啟動並執行流程,回呼函數不必再一層層嵌套。

簡單說,它的思想是,每一個非同步任務立刻返回一個Promise對象,由於是立刻返回,所以可以採用同步操作的流程。這個Promises對象有一個then方法,允許指定回呼函數,在非同步任務完成後調用。

比如,非同步作業f1返回一個Promise對象,它的回呼函數f2寫法如下。

(new Promise(f1)).then(f2);

這種寫法對於多層嵌套的回呼函數尤其方便。

// 傳統寫法

step1(function (value1) {

  step2(value1, function(value2){

    step3(value2,function(value3) {

      step4(value3,function(value4) {

        // ...

      });

    });

  });

});

 

// Promises的寫法

(new Promise(step1))

  .then(step2)

  .then(step3)

  .then(step4);

從上面代碼可以看到,採用Promises介面以後,程式流程變得非常清楚,十分易讀。

注意,為了便於理解,上面代碼的Promise對象的產生格式,做了簡化,真正的文法請參照下文。

總的來說,傳統的回呼函數寫法使得代碼混成一團,變得橫向發展而不是向下發展。Promises規範就是為瞭解決這個問題而提出的,目標是使用正常的程式流程(同步),來處理非同步作業。它先返回一個Promise對象,後面的操作以同步的方式,寄存在這個對象上面。等到非同步作業有了結果,再執行前期寄放在它上面的其他動作。

Promises原本只是社區提出的一個構想,一些外部函數庫率先實現了這個功能。ECMAScript 6將其寫入語言標準,因此目前javascript語言原生支援Promise對象。

前面說過,Promise介面的基本思想是,非同步任務返回一個Promise對象。

Promise對象只有三種狀態。

?   非同步作業“未完成”(pending)

?   非同步作業“已完成”(resolved,又稱fulfilled)

?   非同步作業“失敗”(rejected)

這三種的狀態的變化途徑只有兩種。

?   非同步作業從“未完成”到“已完成”

?   非同步作業從“未完成”到“失敗”。

這種變化只能發生一次,一旦目前狀態變為“已完成”或“失敗”,就意味著不會再有新的狀態變化了。因此,Promise對象的最終結果只有兩種。

?   非同步作業成功,Promise對象傳回一個值,狀態變為resolved。

?   非同步作業失敗,Promise對象拋出一個錯誤,狀態變為rejected。

Promise對象使用then方法添加回呼函數。then方法可以接受兩個回呼函數,第一個是非同步作業成功時(變為resolved狀態)時的回呼函數,第二個是非同步作業失敗(變為rejected)時的回呼函數(可以省略)。一旦狀態改變,就調用相應的回呼函數。

// po是一個Promise對象

po.then(

  console.log,

  console.error

);

上面代碼中,Promise對象po使用then方法綁定兩個回呼函數:操作成功時的回呼函數console.log,操作失敗時的回呼函數console.error(可以省略)。這兩個函數都接受非同步作業傳回的值作為參數。

then方法可以鏈式使用。

po

  .then(step1)

  .then(step2)

  .then(step3)

  .then(

    console.log,

    console.error

  );

上面代碼中,po的狀態一旦變為resolved,就依次調用後面每一個then指定的回呼函數,每一步都必須等到前一步完成,才會執行。最後一個then方法的回呼函數console.log和console.error,用法上有一點重要的區別。console.log只顯示回呼函數step3的傳回值,而console.error可以顯示step1、step2、step3之中任意一個發生的錯誤。也就是說,假定step1操作失敗,拋出一個錯誤,這時step2和step3都不會再執行了(因為它們是操作成功的回呼函數,而不是操作失敗的回呼函數)。Promises對象開始尋找,接下來第一個操作失敗時的回呼函數,在上面代碼中是console.error。這就是說,Promises對象的錯誤有傳遞性。

從同步的角度看,上面的代碼大致等同於下面的形式。

try {

  var v1 = step1(po);

  var v2 = step2(v1);

  var v3 = step3(v2);

  console.log(v3);

} catch (error) {

  console.error(error);

}

ES6提供了原生的Promise建構函式,用來產生Promise執行個體。

下面代碼創造了一個Promise執行個體。

var promise = new Promise(function(resolve, reject) {

  // 非同步作業的代碼

 

  if (/* 非同步作業成功 */){

    resolve(value);

  } else {

    reject(error);

  }

});

Promise建構函式接受一個函數作為參數,該函數的兩個參數分別是resolve和reject。它們是兩個函數,由JavaScript引擎提供,不用自己部署。

resolve函數的作用是,將Promise對象的狀態從“未完成”變為“成功”(即從Pending變為Resolved),在非同步作業成功時調用,並將非同步作業的結果,作為參數傳遞出去;reject函數的作用是,將Promise對象的狀態從“未完成”變為“失敗”(即從Pending變為Rejected),在非同步作業失敗時調用,並將非同步作業報出的錯誤,作為參數傳遞出去。

Promise執行個體產生以後,可以用then方法分別指定Resolved狀態和Reject狀態的回呼函數。

po.then(function(value) {

  // success

}, function(value) {

  // failure

});

Promise的用法,簡單說就是一句話:使用then方法添加回呼函數。但是,不同的寫法有一些細微的差別,請看下面四種寫法,它們的差別在哪裡?

// 寫法一

doSomething().then(function () {

  return doSomethingElse();

});

 

// 寫法二

doSomething().then(function () {

  doSomethingElse();

});

 

// 寫法三

doSomething().then(doSomethingElse());

 

// 寫法四

doSomething().then(doSomethingElse);

為了便於講解,下面這四種寫法都再用then方法接一個回呼函數finalHandler。寫法一的finalHandler回呼函數的參數,是doSomethingElse函數的運行結果。

doSomething().then(function () {

  return doSomethingElse();

}).then(finalHandler);

寫法二的finalHandler回呼函數的參數是undefined。

doSomething().then(function () {

  doSomethingElse();

  return;

}).then(finalHandler);

寫法三的finalHandler回呼函數的參數,是doSomethingElse函數返回的回呼函數的運行結果。

doSomething().then(doSomethingElse())

  .then(finalHandler);

寫法四與寫法一隻有一個差別,那就是doSomethingElse會接收到doSomething()返回的結果。

doSomething().then(doSomethingElse)

  .then(finalHandler);

 

2 promise.then

所有的 promise 對象執行個體裡都有一個then 方法,它是用來跟這個 promise 進行互動的。首先,then 方法會預設調用 resolve() 函數:

new Promise(function(resolve, reject) {

     // Amock async action using setTimeout

     setTimeout(function(){ resolve(10); }, 3000);

})

.then(function(result) {

     console.log(result);

});

 

// From the console:

// 10

then 回調動作的觸發時機是 promise 被執行完。我們還可以串聯 then 方法執行回調操作:

new Promise(function(resolve, reject) {

     // Amock async action using setTimeout

     setTimeout(function(){ resolve(10); }, 3000);

})

.then(function(num) { console.log(‘first then:‘, num); return num * 2; })

.then(function(num) { console.log(‘second then:‘, num); return num * 2; })

.then(function(num) { console.log(‘last then: ‘,num);});

 

// From the console:

// first then: 10

// second then: 20

// lastthen:  40

你會發現,每次 then 調用都會以之前的 then 調用的傳回值為參數。

如果一個 promise 已經執行完成,單then 被再次調用時,回調動作將會被再次執行。而如果這個 promise 裡執行的是reject 回呼函數,這是再調用 then 方法,回呼函數將不會被執行。

3 promise.all

在我們的非同步呼叫時經常有這樣一種情境:我們需要同時調用多個非同步作業,但希望只有等所有的操作都完成後,我們才去執行響應操作——這就是Promise.all 的作用。 Promise.all 方法可以接收多個 promise 作為參數,以數組的形式,當這些 promise 都成功執行完成後才調用回呼函數。

Promise.all([promise1, promise2]).then(function(results){

     //Both promises resolved

})

.catch(function(error) {

     //One or more promises was rejected

});

一個很好的能示範 Promise.all 用法的例子是,執行多個 AJAX 操作(通過 fetch) 調用:

var request1 = fetch(‘/users.json‘);

var request2 = fetch(‘/articles.json‘);

 

Promise.all([request1, request2]).then(function(results) {

     // Both promises done!

});

一旦promise 裡調用了reject函數,也就是執行被拒絕了,沒有能夠正常完成,情況會有些複雜。一旦promise 被拒絕,catch 方法會捕捉到首個被執行的reject函數:

 

var req1 = new Promise(function(resolve, reject){

     // Amock async action using setTimeout

     setTimeout(function(){ resolve(‘First!‘); }, 4000);

});

var req2 = new Promise(function(resolve, reject){

     // Amock async action using setTimeout

     setTimeout(function(){ reject(‘Second!‘); }, 3000);

});

Promise.all([req1, req2]).then(function(results){

     console.log(‘Then:‘, one);

}).catch(function(err) {

     console.log(‘Catch:‘, err);

});

 

// From the console:

// Catch:Second!

4 promise.catch

catch 當一個 promise 被拒絕(reject)時,catch 方法會被執行:

new Promise(function(resolve,reject) {

     // A mock async action using setTimeout

     setTimeout(function() { reject(‘Done!‘); },3000);

})

.then(function(e){ console.log(‘done‘, e); })

.catch(function(e){ console.log(‘catch: ‘, e); });

 

// From theconsole:

// ‘catch:Done!‘

通常我們在 reject 方法裡處理執行失敗的結果,而在catch 裡執行異常結果:

reject(Error(‘Data could not be found‘));

5 promise.race

Promise.race 是一個有趣的函數——它不是等待所有的 promise 被resolve 或 reject,而是在所有的 promise 中只要有一個執行結束,它就會觸發:

var req1 = newPromise(function(resolve, reject) {

     // A mock async action using setTimeout

     setTimeout(function() { resolve(‘First!‘); },8000);

});

var req2 = newPromise(function(resolve, reject) {

     // A mock async action using setTimeout

     setTimeout(function() { resolve(‘Second!‘);}, 3000);

});

Promise.race([req1,req2]).then(function(one) {

     console.log(‘Then: ‘, one);

}).catch(function(one,two) {

     console.log(‘Catch: ‘, one);

});

 

// From theconsole:

// Then:Second!

一個有用的情境是,從多個鏡像伺服器下載資源,一旦有一個返回,其它的返回也就不用處理了。

6 promise實際應用

一個 XMLHttpRequest 調用轉換為基於 Promises 的任務:

// From JakeArchibald‘s Promises and Back:

//http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promisifying-xmlhttprequest

 

function get(url){

  // Return a new promise.

  return new Promise(function(resolve, reject) {

    // Do the usual XHR stuff

    var req = new XMLHttpRequest();

    req.open(‘GET‘, url);

 

    req.onload = function() {

      // This is called even on 404 etc

      // so check the status

      if (req.status == 200) {

        // Resolve the promise with theresponse text

        resolve(req.response);

      }

      else {

        // Otherwise reject with the statustext

        // which will hopefully be a meaningfulerror

        reject(Error(req.statusText));

      }

    };

 

    // Handle network errors

    req.onerror = function() {

      reject(Error("Network Error"));

    };

 

    // Make the request

    req.send();

  });

}

 

// Use it!

get(‘story.json‘).then(function(response){

  console.log("Success!", response);

}, function(error){

  console.error("Failed!", error);

});

Promise.resolve() 和 Promise.reject() 可以直接被調用。有時候,當判斷出 promise 並不需要真正執行時,我們並不需要 使用 new 建立 Promise 對象,而是可以直接調用 Promise.resolve() 和 Promise.reject()。比如:

var userCache = {};

 

function getUserDetail(username) {

  // In both cases, cached or not, apromise will be returned

 

  if (userCache[username]) {

     //Return a promise without the "new" keyword

    return Promise.resolve(userCache[username]);

  }

 

  // Use the fetch API to get theinformation

  // fetch returns a promise

  return fetch(‘users/‘ + username + ‘.json‘)

    .then(function(result) {

      userCache[username] = result;

      return result;

    })

    .catch(function() {

      throw new Error(‘Could not finduser: ‘ + username);

});

 

}

因為 promise 肯定會返回,所以,我們可以使用then 和 catch 方法處理傳回值!

載入圖片

var preloadImage = function (path) {

  return new Promise(function(resolve, reject) {

    var image = newImage();

    image.onload  = resolve;

    image.onerror= reject;

    image.src = path;

  });

};

js之promise講解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.