再談Promise

方法

構造函數

接受的參數是一個帶兩個Function參數的函數,實際的異步代碼編寫在這個函數裏,成功後調用第一個參數,失敗調用第二個;數組

Promise.prototype.catch

當構造函數裏調用到失敗的函數時,會執行該方法的參數,並傳遞錯誤信息;dom

Promise.prototype.then

當構造函數裏調用到成功或者失敗的函數時,會執行該方法的參數,並傳遞結果;異步

Promise.all

並行執行接受的數組,所有同時執行,直到所有都執行完畢,回調成功。async

Promise.race

並行執行接受的數組,所有同時執行,最快的一個執行完畢後,回調成功。函數

 1 private foo(time: number, data: string): Promise<string> {
 2     return new Promise<string>((resolve: (value?: string)=> void, reject: (reason?: any) => void) => {
 3         setTimeout(() => {
 4             console.log("foo execute: " + data);
 5             resolve(data);
 6         }, time);
 7     });
 8 }
 9 
10 Promise.race([this.foo(500, "1"), this.foo(300, "2"), this.foo(600, "3")]).then((value: string) => {
11     console.log("ok " + value);
12 });
13 
14 // 輸出以下:
15 // foo execute: 2
16 // ok 2
17 // foo execute: 1
18 // foo execute: 3

最快的執行後,後續的異步操做不會中斷,也會繼續執行。ui

Promise.reject

獲得一個已經失敗的Promise對象,而且能夠傳遞失敗消息;this

Promise.resolve

獲得一個已經成功的Promise對象,而且能夠傳遞成功後的結果;url

TypeScript下的Promise

TS下的Promise附帶了一個泛型類型,以下Promise<T>,這裏的T表示會傳遞給resolve的參數類型。spa

Promise的細節

直接上一個實例,咱們先編寫一個模擬的異步加載方法:prototype

 1 namespace Res {
 2     /**
 3      * 異步加載數據的方法
 4      */
 5     export function loadRes(url: string): Promise<ResInfo> {
 6         return new Promise<ResInfo>((resolve: (value?: ResInfo)=> void, reject: (reason?: any) => void) => {
 7             // 這裏不使用實際的加載代碼,爲了方便用 setTimeout 來模擬異步的加載操做
 8             setTimeout(() => {
 9                 // 包含 err 字符串的地址都會加載失敗
10                 if (url.indexOf("err") != -1) {
11                     reject("load error!");
12                     return;
13                 }
14                 // 加載成功
15                 let info = new ResInfo();
16                 info.url = url;
17                 info.data = Math.random() + "";
18                 resolve(info);
19             }, 500);
20         });
21     }
22 }
23 
24 class ResInfo {
25     url: string;
26     data: any;
27 }

咱們來看看下面的代碼:

1 Res.loadRes("http://xxx.xxx/common.zip").then((v) => {
2     console.log(v); // ResInfo {url: "http://xxx.xxx/common.zip", data: "0.6981821740164385"}
3 }).then((v) => {
4     console.log(v); // undefined
5 });

咱們發現then方法在不返回新的Promise的時候,繼續再次調用then方法,仍是能夠獲得觸發,這個觸發在上一個then以後,可是已經取不到返回的值了。

若是但願第二個then也能夠獲得異步的返回值,能夠這麼寫:

1 Res.loadRes("http://xxx.xxx/common.zip").then((v) => {
2     console.log(v); // ResInfo {url: "http://xxx.xxx/common.zip", data: "0.7905235849704688"}
3     return Promise.resolve(v);
4 }).then((v) => {
5     console.log(v); // ResInfo {url: "http://xxx.xxx/common.zip", data: "0.7905235849704688"}
6 });

直接返回值也可讓第二個then取到值:

1 Res.loadRes("http://xxx.xxx/common.zip").then((v) => {
2     console.log(v); // ResInfo {url: "http://xxx.xxx/common.zip", data: "0.7905235849704688"}
3     return v;
4 }).then((v) => {
5     console.log(v); // ResInfo {url: "http://xxx.xxx/common.zip", data: "0.7905235849704688"}
6 });

或者改變返回值:

1 Res.loadRes("http://xxx.xxx/common.zip").then((v) => {
2     console.log(v); // ResInfo {url: "http://xxx.xxx/common.zip", data: "0.6981821740164385"}
3     return "hello";
4 }).then((v) => {
5     console.log(v); // hello
6 });

能夠經過判斷轉變爲一個異常拋出:

 1 Res.loadRes("http://xxx.xxx/common.zip").then((v) => {
 2     console.log(v); // ResInfo {url: "http://xxx.xxx/common.zip", data: "0.6981821740164385"}
 3     if (true) {
 4         return Promise.reject("error 1000");
 5     }
 6 }).then((v) => {
 7     console.log(v); // 這裏已經不會被執行到了
 8 }).catch((err) => {
 9     console.log(err); // error 1000
10 });

async和await

async 的方法就能夠看作一個封裝好的 Promise 對象,調用該方法就會馬上獲得一個 Promise 對象,該方法返回的值是 then 的成功回調的參數;

當須要對一個 async 方法或者返回 Promise 對象的方法進行異步等待時,就要加上 await 關鍵字,同時加了 await 關鍵字的方法要變成用 async 修飾的方法;

若是不加 await 關鍵字,就要使用 then 方法來監聽異步的回調;

async 和 await 能夠看作Promise的編寫語法糖;

下面直接上實例:

 1 private async loadAll(): Promise<string> {
 2     console.log("加載前的初始化");
 3     await Res.loadRes("http://xxx.xxx/common.zip");
 4     console.log("加載通用資源成功");
 5     let info = await Res.loadRes("http://xxx.xxx/ui.zip");
 6     console.log("加載 " + info.url + "成功: " + info.data);
 7     await Res.loadRes("http://xxx.xxx/code.zip");
 8     console.log("最後一個資源加載成功");
 9 
10     return "complete";
11 }
12 
13 this.loadAll()
14 .then((result?: string) => {
15     console.log("加載所有完畢: " + result);
16 })
17 .catch((reason?: any) => {
18     console.log("加載失敗: " + reason);
19 });

實際上就是Promise的簡寫形式,也更方便閱讀和理解。

另一些須要關注的細節

Promise的異步處理邏輯函數中當即調用resolve,是同步執行麼?

咱們來看下面的例子:

 1 private foo() {
 2     return new Promise((r:Function)=>{
 3         console.log("2");
 4         return r("resolve");
 5     });
 6 }
 7 
 8 console.log("1");
 9 this.foo().then(()=>{
10     console.log("3");
11 });
12 console.log("4");

輸出:

1 1
2 2
3 4
4 3

從輸出來看調用了resolve以後,並無當即觸發then的回調,而是繼續執行下面的方法(輸出了4),以後才調用了then的回調(輸出了3),因此當即返回後,並非同步當即執行then的回調,但then的回調並無等到下一個刷新(即下一幀)才調用,而是在本幀就會調用,只是調用放在本幀的稍後的時間裏進行;

多個其它地方的then方法能夠同時等待同一個Promise麼?

目前爲止,咱們都是等待一個新建立的Promise,若是多個方法都在等待同一個Promise會怎麼樣,咱們看看下面的例子:

 1 private _p: Promise<any>;
 2 
 3 private foo1() {
 4     return this._p;
 5 }
 6 
 7 async foo2() {
 8     await this.foo1();
 9     console.log("foo2 1");
10     await this.foo1();
11     console.log("foo2 2");
12     await this.foo1();
13     console.log("foo2 3");
14 }
15 
16 async foo3() {
17     await this.foo1();
18     console.log("foo3 1");
19     await this.foo1();
20     console.log("foo3 2");
21 }
22 
23 this._p = new Promise((r:Function)=>{
24     setTimeout(()=>{
25         console.log("異步執行完畢");
26         return r("data");
27     },1000);
28 });
29 
30 this.foo2().then(()=>{console.log("foo2 e");});
31 this.foo3().then(()=>{console.log("foo3 e");});

輸出以下:

1 異步執行完畢
2 foo2 1
3 foo3 1
4 foo2 2
5 foo3 2
6 foo3 e
7 foo2 3
8 foo2 e

咱們發現多個方法能夠等待同一個Promise,該Promise成功或者失敗時,全部等待該Promise的方法都會繼續執行。

若是await一個已經執行完成的Promise時,會當即獲得結束的執行。

Promise只會執行第一次的回調

當我500毫秒時,調用reject,1000毫秒時,調用resolve,then裏面的方法是不會執行的。

 1 function foo() {
 2     return new Promise((resolve, reject) => {
 3         setTimeout(()=>{
 4             console.log("error");
 5             reject();
 6         }, 500);
 7         setTimeout(()=>{
 8             console.log("resolve");
 9             resolve();
10         }, 1000);
11     });
12 }
13 
14 foo().then(()=>{
15     console.log("success");
16 })
17 .catch(()=>{
18     console.log("fail");
19 });
相關文章
相關標籤/搜索