Promise

1.Promise 的含义

Promise 是异步编程的一种解决方案

Promise对象有以下两个特点。

(1)对象的状态不受外界影响。Promise对象代表一个异步操作,有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)

(2)一旦状态改变,就不会再变,任何时候都可以得到这个结果。Promise对象的状态改变,只有两种可能:从pending变为fulfilled和从pending变为rejected。

2.基本用法

ES6 规定,Promise对象是一个构造函数,用来生成Promise实例。

constpromise=newPromise(function(resolve,reject) {

// ... some code

if(/* 异步操作成功 */){

resolve(value);

}else{

reject(error);

  }

});

Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve和reject。它们是两个函数,由 JavaScript 引擎提供,不用自己部署

Promise实例生成以后,可以用then方法分别指定resolved状态和rejected状态的回调函数。

promise.then(function(value) {

// success

},function(error) {

// failure

});

then方法可以接受两个回调函数作为参数。第一个回调函数是Promise对象的状态变为resolved时调用,第二个回调函数是Promise对象的状态变为rejected时调用。这两个函数都是可选的,不一定要提供。它们都接受Promise对象传出的值作为参数。

functiontimeout(ms) {

returnnewPromise((resolve,reject)=>{

setTimeout(resolve,ms,'done');

  });

}

timeout(100).then((value)=>{

console.log(value);

});

上面代码中,timeout方法返回一个Promise实例,表示一段时间以后才会发生的结果。过了指定的时间(ms参数)以后,Promise实例的状态变为resolved,就会触发then方法绑定的回调函数。

Promise 新建后就会立即执行。

letpromise=newPromise(function(resolve,reject) {

console.log('Promise');

resolve();

});

promise.then(function() {

console.log('resolved.');

});

console.log('Hi!');

// Promise

// Hi!

// resolved

上面代码中,Promise 新建后立即执行,所以首先输出的是Promise。然后,then方法指定的回调函数,将在当前脚本所有同步任务执行完才会执行,所以resolved最后输出。

下面是异步加载图片的例子。

functionloadImageAsync(url) {

returnnewPromise(function(resolve,reject) {

constimage=newImage();

image.onload=function() {

resolve(image);

   };

image.onerror=function() {

reject(newError('Could not load image at '+url));

   };

image.src=url;

  });

}

上面代码中,使用Promise包装了一个图片加载的异步操作。如果加载成功,就调用resolve方法,否则就调用reject方法。

3.Promise.prototype.then()

Promise 实例具有then方法,也就是说,then方法是定义在原型对象Promise.prototype上的。它的作用是为 Promise 实例添加状态改变时的回调函数。前面说过,then方法的第一个参数是resolved状态的回调函数,第二个参数是rejected状态的回调函数,它们都是可选的。

then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。

getJSON("/posts.json").then(function(json) {

returnjson.post;

}).then(function(post) {

// ...

});

上面的代码使用then方法,依次指定了两个回调函数。第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。

采用链式的then,可以指定一组按照次序调用的回调函数。这时,前一个回调函数,有可能返回的还是一个Promise对象(即有异步操作),这时后一个回调函数,就会等待该Promise对象的状态发生变化,才会被调用。

getJSON("/post/1.json").then(function(post) {

returngetJSON(post.commentURL);

}).then(function(comments) {

console.log("resolved: ",comments);

},function(err){

console.log("rejected: ",err);

});

上面代码中,第一个then方法指定的回调函数,返回的是另一个Promise对象。这时,第二个then方法指定的回调函数,就会等待这个新的Promise对象状态发生变化。如果变为resolved,就调用第一个回调函数,如果状态变为rejected,就调用第二个回调函数。

如果采用箭头函数,上面的代码可以写得更简洁。

getJSON("/post/1.json").then(

post=>getJSON(post.commentURL)

).then(

comments=>console.log("resolved: ",comments),

err=>console.log("rejected: ",err)

);

4.Promise.prototype.catch()

Promise.prototype.catch()方法是.then(null, rejection)或.then(undefined, rejection)的别名,用于指定发生错误时的回调函数。

getJSON('/posts.json').then(function(posts) {

// ...

}).catch(function(error) {

// 处理 getJSON 和 前一个回调函数运行时发生的错误

console.log('发生错误!',error);

});

上面代码中,getJSON()方法返回一个 Promise 对象,如果该对象状态变为resolved,则会调用then()方法指定的回调函数;如果异步操作抛出错误,状态就会变为rejected,就会调用catch()方法指定的回调函数,处理这个错误。另外,then()方法指定的回调函数,如果运行中抛出错误,也会被catch()方法捕获。

p.then((val)=>console.log('fulfilled:',val))

.catch((err)=>console.log('rejected',err));

// 等同于

p.then((val)=>console.log('fulfilled:',val))

.then(null, (err)=>console.log("rejected:",err));

下面是一个例子。

constpromise=newPromise(function(resolve,reject) {

thrownewError('test');

});

promise.catch(function(error) {

console.log(error);

});

// Error: test

上面代码中,promise抛出一个错误,就被catch()方法指定的回调函数捕获。注意,上面的写法与下面两种写法是等价的。

// 写法一

constpromise=newPromise(function(resolve,reject) {

try{

thrownewError('test');

}catch(e) {

reject(e);

  }

});

promise.catch(function(error) {

console.log(error);

});

// 写法二

constpromise=newPromise(function(resolve,reject) {

reject(newError('test'));

});

promise.catch(function(error) {

console.log(error);

});

比较上面两种写法,可以发现reject()方法的作用,等同于抛出错误。

5.Promise.prototype.finally()

finally()方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。该方法是 ES2018 引入标准的。

promise

.then(result=>{···})

.catch(error=>{···})

.finally(()=>{···});

上面代码中,不管promise最后的状态,在执行完then或catch指定的回调函数以后,都会执行finally方法指定的回调函数。

6.Promise.all()

Promise.all()方法用于将多个 Promise 实例,包装成一个新的 Promise 实例。

constp=Promise.all([p1,p2,p3]);

p的状态由p1、p2、p3决定,分成两种情况。

(1)只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数。

(2)只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。

// 生成一个Promise对象的数组

constpromises=[2,3,5,7,11,13].map(function(id) {

returngetJSON('/post/'+id+".json");

});

Promise.all(promises).then(function(posts) {

// ...

}).catch(function(reason){

// ...

});

上面代码中,promises是包含 6 个 Promise 实例的数组,只有这 6 个实例的状态都变成fulfilled,或者其中有一个变为rejected,才会调用Promise.all方法后面的回调函数。

7.Promise.race()

Promise.race()方法同样是将多个 Promise 实例,包装成一个新的 Promise 实例。

constp=Promise.race([p1,p2,p3]);

上面代码中,只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。

Promise.race()方法的参数与Promise.all()方法一样,如果不是 Promise 实例,就会先调用下面讲到的Promise.resolve()方法,将参数转为 Promise 实例,再进一步处理。

下面是一个例子,如果指定时间内没有获得结果,就将 Promise 的状态变为reject,否则变为resolve。

constp=Promise.race([

fetch('/resource-that-may-take-a-while'),

newPromise(function(resolve,reject) {

setTimeout(()=>reject(newError('request timeout')),5000)

  })

]);

p

.then(console.log)

.catch(console.error);

上面代码中,如果 5 秒之内fetch方法无法返回结果,变量p的状态就会变为rejected,从而触发catch方法指定的回调函数

8.Promise.allSettled()

Promise.allSettled()方法接受一组 Promise 实例作为参数,包装成一个新的 Promise 实例。只有等到所有这些参数实例都返回结果,不管是fulfilled还是rejected,包装实例才会结束。该方法由 ES2020 引入。

constpromises=[

fetch('/api-1'),

fetch('/api-2'),

fetch('/api-3'),

];

awaitPromise.allSettled(promises);

removeLoadingIndicator();

上面代码对服务器发出三个请求,等到三个请求都结束,不管请求成功还是失败,加载的滚动图标就会消失。

constresolved=Promise.resolve(42);

constrejected=Promise.reject(-1);

constallSettledPromise=Promise.allSettled([resolved,rejected]);

allSettledPromise.then(function(results) {

console.log(results);

});

// [

//    { status: 'fulfilled', value: 42 },

//    { status: 'rejected', reason: -1 }

// ]

上面代码中,Promise.allSettled()的返回值allSettledPromise,状态只可能变成fulfilled。它的监听函数接收到的参数是数组results。该数组的每个成员都是一个对象,对应传入Promise.allSettled()的两个 Promise 实例。每个对象都有status属性,该属性的值只可能是字符串fulfilled或字符串rejected。fulfilled时,对象有value属性,rejected时有reason属性,对应两种状态的返回值。

9.Promise.any()

ES2021 引入了Promise.any()方法为参数,包装成一个新的 Promise 实例返回。

Promise.any([

fetch('https://v8.dev/').then(()=>'home'),

fetch('https://v8.dev/blog').then(()=>'blog'),

fetch('https://v8.dev/docs').then(()=>'docs')

]).then((first)=>{// 只要有一个 fetch() 请求成功

console.log(first);

}).catch((error)=>{// 所有三个 fetch() 全部请求失败

console.log(error);

});

只要参数实例有一个变成fulfilled状态,包装实例就会变成fulfilled状态;如果所有参数实例都变成rejected状态,包装实例就会变成rejected状态。

Promise.any()跟Promise.race()方法很像,只有一点不同,就是Promise.any()不会因为某个 Promise 变成rejected状态而结束,必须等到所有参数 Promise 变成rejected状态才会结束。

下面是Promise()与await命令结合使用的例子。

constpromises=[

fetch('/endpoint-a').then(()=>'a'),

fetch('/endpoint-b').then(()=>'b'),

fetch('/endpoint-c').then(()=>'c'),

];

try{

constfirst=awaitPromise.any(promises);

console.log(first);

}catch(error) {

console.log(error);

上面代码中,Promise.any()方法的参数数组包含三个 Promise 操作。其中只要有一个变成fulfilled,Promise.any()返回的 Promise 对象就变成fulfilled。如果所有三个操作都变成rejected,那么await命令就会抛出错误。

10.Promise.resolve()

有时需要将现有对象转为 Promise 对象,Promise.resolve()方法就起到这个作用。

constjsPromise=Promise.resolve($.ajax('/whatever.json'));

上面代码将 jQuery 生成的deferred对象,转为一个新的 Promise 对象。

Promise.resolve()等价于下面的写法。

Promise.resolve('foo')

// 等价于

newPromise(resolve=>resolve('foo'))

Promise.resolve()方法的参数分成四种情况。

(1)参数是一个 Promise 实例

如果参数是 Promise 实例,那么Promise.resolve将不做任何修改、原封不动地返回这个实例。

(2)参数是一个thenable对象

thenable对象指的是具有then方法的对象,比如下面这个对象。

letthenable={

then:function(resolve,reject) {

resolve(42);

  }

};

Promise.resolve()方法会将这个对象转为 Promise 对象,然后就立即执行thenable对象的then()方法。

letthenable={

then:function(resolve,reject) {

resolve(42);

  }

};

letp1=Promise.resolve(thenable);

p1.then(function(value) {

console.log(value);// 42

});

上面代码中,thenable对象的then()方法执行后,对象p1的状态就变为resolved,从而立即执行最后那个then()方法指定的回调函数,输出42。

(3)参数不是具有then()方法的对象,或根本就不是对象

如果参数是一个原始值,或者是一个不具有then()方法的对象,则Promise.resolve()方法返回一个新的 Promise 对象,状态为resolved。

constp=Promise.resolve('Hello');

p.then(function(s) {

console.log(s)

});

// Hello

上面代码生成一个新的 Promise 对象的实例p。由于字符串Hello不属于异步操作(判断方法是字符串对象不具有 then 方法),返回 Promise 实例的状态从一生成就是resolved,所以回调函数会立即执行。Promise.resolve()方法的参数,会同时传给回调函数。

(4)不带有任何参数

Promise.resolve()方法允许调用时不带参数,直接返回一个resolved状态的 Promise 对象。

所以,如果希望得到一个 Promise 对象,比较方便的方法就是直接调用Promise.resolve()方法。

constp=Promise.resolve();

p.then(function() {

// ...

});

上面代码的变量p就是一个 Promise 对象。

需要注意的是,立即resolve()的 Promise 对象,是在本轮“事件循环”(event loop)的结束时执行,而不是在下一轮“事件循环”的开始时。

setTimeout(function() {

console.log('three');

},0);

Promise.resolve().then(function() {

console.log('two');

});

console.log('one');

// one

// two

// three

上面代码中,setTimeout(fn, 0)在下一轮“事件循环”开始时执行,Promise.resolve()在本轮“事件循环”结束时执行,console.log('one')则是立即执行,因此最先输出。

11.Promise.reject()

Promise.reject(reason)方法也会返回一个新的 Promise 实例,该实例的状态为rejected。

constp=Promise.reject('出错了');

// 等同于

constp=newPromise((resolve,reject)=>reject('出错了'))

p.then(null,function(s) {

console.log(s)

});

// 出错了

上面代码生成一个 Promise 对象的实例p,状态为rejected,回调函数会立即执行。

Promise.reject()方法的参数,会原封不动地作为reject的理由,变成后续方法的参数。

Promise.reject('出错了')

.catch(e=>{

console.log(e==='出错了')

})

// true

上面代码中,Promise.reject()方法的参数是一个字符串,后面catch()方法的参数e就是这个字符串。

12.Promise.try()

实际开发中,经常遇到一种情况:不知道或者不想区分,函数f是同步函数还是异步操作,但是想用 Promise 来处理它。因为这样就可以不管f是否包含异步操作,都用then方法指定下一步流程,用catch方法处理f抛出的错误。一般就会采用下面的写法。

Promise.resolve().then(f)

上面的写法有一个缺点,就是如果f是同步函数,那么它会在本轮事件循环的末尾执行。

constf=()=>console.log('now');

Promise.resolve().then(f);

console.log('next');

// next

// now

上面代码中,函数f是同步的,但是用 Promise 包装了以后,就变成异步执行了。

你可能感兴趣的:(Promise)