再談Promise


方法

構造函數

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

Promise.prototype.catch

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

Promise.prototype.then

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

Promise.all

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

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

最快的執行后,后續的異步操作不會中斷,也會繼續執行。

Promise.reject

得到一個已經失敗的Promise對象,並且可以傳遞失敗消息;

Promise.resolve

得到一個已經成功的Promise對象,並且可以傳遞成功后的結果;

TypeScript下的Promise

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

Promise的細節

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

 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 });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM