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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值