JavaScript:理解Promise方法

 什麼是promise?

Promise的核心思想是表明異步操做的一個結果,而且promise具備三個狀態(pending初始狀態,fulfilled成功狀態,rejected失敗狀態)。咱們能夠理解爲使用promise能夠實現非阻塞io的功能,根據三個不一樣的狀態,咱們能夠知道回調函數實如今哪一個過程。segmentfault

Promise.prototype.then

源碼分析:api

 1 this.then = function(onFulfilled) {
 2     if (typeof onFulfilled !== "function") return this;
 3     return new Promise(function(resolve, reject) {
 4       asap(function() {
 5         try {
 6           resolve(onFulfilled(value));
 7         } catch (ex) {
 8           reject(ex);
 9         }
10       });
11     });
12 };
13 
14 this.then = function(onFulfilled, onRejected) {
15     return new self.constructor(function(resolve, reject) {
16       handle(new Handler(onFulfilled, onRejected, resolve, reject));
17     });
18 };
19 
20 ValuePromise.prototype = Promise.prototype;

  咱們知道.then先是以對象的屬性實現的方法,隨後是以繼承的方式實現的方法,因此then方法能夠具備一個參數.then(onFulfilled),又可具備二個參數.then(onFulfilled,onRejected),第一個參數爲操做成功的回調函數,而且第二個參數是操做失敗的回調函數,而後從上面的handle方法能夠看出then的二個參數以數組對象的形式保存在一個隊列(deferreds)裏面,而後從隊列裏面處理then方法。數組

 

.then鏈式調用

例子(略因爲非鏈式每次都是promise迭代而已):promise

 1 // 新建一個返回promise對象的函數
 2 var p1 = function constructorpromise (a) {
 3   return new Promise(function(resolve, reject) {
 4       resolve(1)
 5   });
 6 }
 7 
 8 // 實現鏈式調用
 9 var con = constructorpromise(2)
10 con
11 .then(function(a) {
12   var second = document.getElementsByClassName('part-second')[0]
13   second.innerText = a
14   return a + 2
15 })
16 .then(function(b) {
17   var first = document.getElementsByClassName('part-first')[0]
18   first.innerText = b
19 })

  注意以上有二個then方法實現的回調,第一個then方法調用傳參是從promise中resolve回調傳入的參數值1,第二個then方法調用傳參是上一個then方法內部return傳遞下來的值3(return a +2),所以第二個then參數得到的結果爲3。(切記:若是是鏈式調用then,那麼從第二個then開始的參數都是從上一個then的返回的結果,若是上一個then沒有return,那麼下一個then的參數爲undefined)異步

 

Promise.all()

源碼分析:函數

 1 Promise.all = function(arr) {
 2       var args = Array.prototype.slice.call(arr);
 3       return new Promise(function(resolve, reject) {
 4         if (args.length === 0) return resolve([]);
 5         var remaining = args.length;
 6         function res(i, val) {
 7           try {
 8             if (val && (typeof val === "object" || typeof val === "function")) {
 9               var then = val.then;
10               if (typeof then === "function") {
11                 then.call(val, function(val) {
12                   res(i, val);
13                 }, reject);
14                 return;
15               }
16             }
17             args[i] = val;
18             if (--remaining === 0) {
19               resolve(args);
20             }
21           } catch (ex) {
22             reject(ex);
23           }
24         }
25         for (var i = 0; i < args.length; i++) {
26           res(i, args[i]);
27         }
28       });
29     };

  從以上能夠看出,當all的方法內參數爲空時(args.length === 0),就會返回一個resolve方法的迭代對象。若是不爲空,且all方法的數組上也不是promise時,那麼就會輸出值args[i] = val;也就是說返回初始值pending。若是all方法的數組項是promise時,就會回調resolve()並返回每一項的結果。源碼分析

例子:this

1 var promise = Promise.resolve(3);
2 Promise.all([true, promise]).then(values => {
3   console.log(values); // [true, 3]
4 });

 

Promise.race([])

源碼分析:spa

1 Promise.race = function(values) {
2   return new Promise(function(resolve, reject) {
3     values.forEach(function(value) {
4       Promise.resolve(value).then(resolve, reject);
5     });
6   });
7 };

  其實.race方法內部的數組每一項若是都用promise的resolve方法實現的迭代,那麼數組內每一項promise的狀態都會發生改變,就像race英文的意思"賽跑,競爭",表示promise哪一項先執行resolve回調,哪一項promise就會先執行回調函數並返回resolve結果。prototype

例子:

 1 var p1 = new Promise(function(resolve, reject) {
 2   setTimeout(resolve, 500, "one");
 3 });
 4 var p2 = new Promise(function(resolve, reject) {
 5   setTimeout(resolve, 100, "two");
 6 });
 7 
 8 Promise.race([p1, p2]).then(function(value) {
 9   console.log(value); // "two"
10   // Both resolve, but p2 is faster
11 });

 

參考:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise#參見

https://segmentfault.com/a/1190000007032448#articleHeader10

https://www.promisejs.org/api/

相關文章
相關標籤/搜索