Promise是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最早提出和实现,ES6将其写进了语言标准,统一了用法,原生提供了Promise对象。
promise的特点:
- 对象的状态不会受到外界所影响,
Promise对象代表一次异步操作,只会有三种状态Pending(进行中),Fulfilled(已成功),Rejected(失败)。只有异步操作的结果可以决定Promise对象的状态,任何其他操作都无法改变这个状态。 -
Promise对象的状态变化只会有两种可能:(1)Pending变成Fulfilled(2)Pending变成Rejected。只要这两种情况任意一个发生,Promise的状态就会固定,不会再发生变化了。 - 如果状态已经发生的改变,再给给期添加回调函数,依然可以得到结果。这与
event不同,事件一旦错过就没有了。 -
缺点: a.
Promise一旦创建就会立即执行,无法中途取消。b. 如果不设置回调函数,Promise内部发生的错误,不会反应到外部。c.Pending状态时,无法得知当前进展到哪一状态。
基本用法
- 创建一个
Promise实例;
var promise = new Promise(function (resolve, reject) {
if(/*成功*/) {
resolve(value);
} else {
reject(error);
}
})
Promise实例创建完毕,我们需要通过then方法分别指定Resolved和Rejected状态的回调函数。
promise.then(function () {
// success code
}, function () {
// failure code
})
then 方法可以接受两个参数,第一个参数对应成功的回调函数,第二个对应的是失败的回调函数,并且第二个参数的可选的,不一定需要传递。
-
Promise新建以后就会立即执行。
var promise = new Promise(function (resolve, reject) {
resolve();
console.log('promise')
})
promise.then(function () {
console.log('resolved')
})
console.log('hi');
// 执行结果:
// promise
// hi
// resolved
then 方法指定的回调函数,将在当前脚本所同步任务执行完成才会执行,所以resolved最后输出。
Promise.prototype.then()
Promise实例具有then方法,也就是then方法是定义在Promise的原型对象上的,他的作用就是添加状态改变时的回调函数。
注意:then方法返回的是一新的Promise实例(不是原来的那个Promise实例),因此可以链式调用。
var getJSON = function (url) {
var promise = new Promise(function (resolve, reject) {
var client = new XMLHttpRequest();
client.open('GET', url);
client.onreadystatechange = handler;
client.responseType = 'json';
client.setRequestHeader('Accept', 'application/json');
client.send();
function handler() {
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response)
} else {
reject(new Error(this.statusText))
}
}
})
return promise;
}
getJSON('/posts.json').then(function (json) {
return json.post;
}).then(function(post){
//post 是上一个回调函数传过来的
})
上面的代码使用then方法,依次指定了两个回调函数,第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。
getJSON('/post/1.json').then(function(post){
return getJSON('/post/2.json')
}).then(function(post){
console.log('resloved')
}, function(err){
console.log('rejected')
})
上面的代码,第一个then方法返回了Promise对象,这时,第二个then指定的回调函数,要等到这个Promise对象状态改变时才会触发。
Promise.prototype.catch()
Promise.prototype.catch方法是.then(null, fn)的别名,用于指定发生错误的回调函数。
getJSON('/post.json').then(function(){
// code
}).catch(function(err){
console.log(err)
})
getJSON返回一个Promise对象,如果是成功状态就会走then里面设置的回调函数,如果失败了就会走catch设置的回调函数,如果then指定的回调函数里面出错了,也会被catch所捕获,调用catch设置的回调函数处理。
p.then(function(){
//code
}).catch(function(){
//code
})
// 等同于
p.then(function(){
// code
}).then(null, function(){
//code
})
// 第一种写法
var promise = new Promise(function(resolve, reject){
try {
throw new Error('test')
} catch (e) {
reject(e)
}
})
promise.catch(function(err){
console.log(err)
})
// 第二种写法
var promise = new Promise(function(resolve, reject){
reject(new Error('test'))
})
promise.catch(function(error){
console.log(error)
})
上面两种写法是等价的,可以看出reject方法作用,等同于抛出错误。
var promise = new Promise(function(resolve, reject){
resolve('ok');
throw new Error('test')
})
promise.then(function(value){
console.log(value)
}).catch(function(err){
console.log(err)
})
// ok
Promise在resolve语句后面再抛出错误,是不会被catch捕获的,等于没有抛出。
getJSON('/post/1.json').then(function(post){
return getJSON('/post/2.json')
}).then(function(json2){
// code
}).catch(function(e){
console.log(e)
// 捕获前面三个promise对象的错误
})
Promise对象的错误具有“冒泡”的性质,会向后面一直传递,直到被捕获为止。
//不推荐的写法
promise.then(function(data){
//success
}, function(err){
// failure
})
// 推荐写法
promise.then(function(data){
//success
}).catch(function(err){
console.log(err)
})
第二种方法优于第一种写法,理由是第二种可以捕获前面then 里面的错误,语法页更贴近(try/catch)。
var someAsyncThing = function() {
return new Promise(function() {
resolve(x + 2)
})
}
someAsyncThing().then(function() {
console.log('..')
})
上面的代码中,someAsynicThing函数产生的Promise对象会报错,但是没有指定catch方法这个错误是不会被捕获的,也不会被传递到外层的。
var promise = new Promise(function(resolve, reject) {
resolve('ok');
setTimeout(function(){
throw new Error('test')
}, 0)
})
promise.then(function(value) {
console.log(value);
}).catch(function(err) {
console.log(err);
})
// ok
// VM672:4 Uncaught Error: test
Promise指定在下轮的事件循环里面在抛出一个错误,到那个时候Promise的运行已经结束,所以这个错误会在函数体外抛出,冒泡到最外层成为未捕获的错误。
var someAsyncthing = function() {
return new Promise(function(resolve, reject){
// 将报错,x没有申明
resolve(x + 2)
})
}
someAsyncthing().catch(function(err){
console.log('err:', err)
return '123'
}).then(function(str){
console.log('ok', str)
})
// err: ReferenceError: x is not defined
// at <anonymous>:4:13
// at Promise (<anonymous>)
// at someAsyncthing (<anonymous>:2:10)
// at <anonymous>:7:1
//ok 123
catch方法返回的还是一个Promise对象,因此后面还是可以接着调用then方法。
var someAsyncthing = function() {
return new Promise(function(resolve, reject){
resolve(2)
})
}
someAsyncthing().catch(function(err){
console.log('err:', err)
return '123'
}).then(function(str){
console.log('ok', str)
// x 未定义会报错
return x;
})
//ok 2
//ReferenceError: x is not defined
// at <anonymous>:12:3
// at <anonymous>
上面代码,Promise里面没有错误,就会跳过catch的方法,直接执行下面的then方法,then里面在出错就与前面的catch无关了,错误也不会被捕获。
var someAsyncthing = function() {
return new Promise(function(resolve, reject){
resolve(2)
})
}
someAsyncthing().catch(function(err){
console.log('err:', err)
// x 未定义
return x
}).then(function(str){
console.log('ok', str)
})
// ok 2
catch里面出了错误,因为后面没有catch了,导致这个错误不会被捕获,也不会被传递到最外层。
总结: 为了尽可能多的捕获到错误,应该将catch写在所有then的最后面,这样不仅可以捕获到promise的错误,也能捕获到前面then里面错误.
Promise.all()
Promise.all方法用于将多个Promise实例,包装成一个新的Promise实例。
var p = Promise.all([p1, p2, p3])
Promise.all接受一个数组作为参数,p1,p2,p3都是Promise实例,如果不是,就会先调用Promise.resolve方法,将其转为Promise实例。(Promise.all的参数可以不一定是数组,但一定是要实现Iterator接口的,且返回的每个成员都是Promise实例)
p的状态是由p1,p2,p3决定的:
- 只有
p1,p2,p3的状态都变成fulfilled,p的状态就变成fulfilled,此时p1,p2,p3的返回组成一个数组,传递给p的回调函数。 - 只有
p1,p2,p3中有一个的状态都变成rejected,p的状态就变成rejected,此时第一个变成rejected的实例的返回值,传递给p的回调函数。
var a = function(){
var t = ~~(Math.random()*1000)
return new Promise(function(resolve, reject){
setTimeout(function(){
console.log(t)
resolve(t)
},t)
})
}
var p1 = a(); var p2 = a();
Promise.all([p1,p2]).then(([p1,p2])=>{console.log(123, p1,p2)})
// 562
// 879
// 123 879 562
上面p1和p2是两个异步的操作,只有等到两个结果都返回了才会触发Promise.all的then的方法
// 由于是随机数要多试几次
var a = function(){
var t = ~~(Math.random()*1000)
return new Promise(function(resolve, reject){
setTimeout(function(){
console.log(t)
if(t < 500){
reject(new Error('<500'))
}
resolve(t)
},t)
})
}
// 如果出错,p1将不是a函数返回的Promise,而是catch返回的promise
var p1 = a().catch((err) => {console.log('err:', err)});
var p2 = a().catch((err) => {console.log('err:', err)});
Promise.all([p1,p2]).then(([p1,p2])=>{console.log(123, p1,p2)}).catch((err) => {console.log('all',err)})
//7 a 里面的输出
//err: Error: <500 p1 的catch的输出
// at <anonymous>:7:12
// 687 a 里面的输出
//123 undefined 687 Promise.all的then输出
上面p1和p2都有可能会Rejected,一旦Rejected就会被他们的catch所捕获,然后就会返回一个全新的Promise对象不再是原来的那个,全新的实例执行完catch以后也会变成Resolved, 导致Promise.all方法里面的两个实例都是Resolved,则会走Promise.all的then方法,而不会是catch方法。
Promise.race()
Promise.race方法同样是将多个Promise的实例,包装成一个新的Promise实例。
var p = Promise.race([p1,p2,p3])
上面代码,只要p1,p2,p3之中有一个实例率先改变了状态,p的状态就会跟着改变,那个率先改变的Promise实例的返回值,就传递给p的回调函数。
他处理参数的方法的原则和Promise.all是一样的。
var a = function(){
var t = ~~(Math.random()*1000)
return new Promise(function(resolve, reject){
setTimeout(function(){
console.log(t)
resolve(t)
},t)
})
}
var p1 = a()
var p2 = a()
Promise.race([p1,p2]).then(t =>{console.log(123, t)})
// 87 a 函数输出
// 123 87 Promise.race的then输出
// 591 a 函数输出
Promise.resolve()
有时需要将现有的对象转化成Promise对象,Promise.resolve方法就起到这个作用。
var jqPromise = Promise.resolve($.ajax('/1.json'))
上面的代码将jQuery生成的deferred对象,转成一个新的Promise对象。
Promise.resolve('foo')
// 等价于
new Promise(function(resolve, reject){
resolve('foo')
})
Promise.resolve方法的参数分为四种情况
a. 参数是一个Promise实例
如果参数是一个Promise实例,那么Promise.resolve将不做任何修改,原封不动的返回这个实例。
b. 参数是一个thenable对象
thenable对象是指具有then方法的对象,例如:
// thenable 对象
let thenable = {
then: function(resolve, reject){
resolve(42)
}
}
let p1 = Promise.resolve(thenable);
p1.then(function(value){
console.log(value) // 42
})
thenable对象的then方法执行以后,对象p1的状态就会变成resolved,从而立即执行最后的那个then方法指定的函数,输出42
c. 参数不是具有then方法的对象,或根本就不是对象
如果参数是一个原始值,或者是一个不具有then方法的对象,则Promise.resolve方法返回一个新的Promise对象,状态为Resolved.
var p = Promise.resolve('hello')
p.then(function(s){
console.log(s)
})
// hello
上面的代码生成一个新的Promise对象的实例p,由于字符串hello不属于异步操作(判断方法字符串不具有then方法),返回的Promise实例的状态从一生成就是Resolved,所以回调函数立即执行。Promise.resolve方法的参数,会同时传回给回调函数。
d. 不带任何参数
Promise.resolve方法允许调用时不带任何参数,直接返回一个Resolved状态的Promise对象。
注意: 立即resolve的Promise对象,实在本轮事件循环的结束时,而不是在下一轮事件循环的开始时
setTimeout(function(){
console.log('setTimeout')
}, 0)
Promise.resolve().then(function(){
console.log('Promise.resolve')
})
console.log('console.log()')
// console.log() 顺序执行
// Promise.resolve 本轮事件循环的尾部
// setTimeout 下轮事件循环的开始
setTimeout(fn, 0)实在下一轮事件循环的开始的时候执行的,Promise.resolve()实在本轮事件循环的结束时执行,console.log()立即执行,所以最先输出。
Promise.reject()
跟Promise.resolve方法类似,生成相对的状态为Rejected的Promise实例。
var p = Promise.reject('出错了');
// 等同于
var p = new Promise((resolve, reject) => reject('出错了'))
p.then(null, function (s) {
console.log(s)
});
// 出错了
生成的p的状态为Rejected的,回调函数立马执行。
注意: Promise.reject()方法的参数,会原封不动的作为reject的理由,比那成后续方法的参数,这一点与Promise.resolve方法不一致
const thenable = {
then(resolve, reject) {
reject('出错了');
}
};
Promise.reject(thenable)
.catch(e => {
console.log(e === thenable)
})
// true
两个有用的附加方法
ES6的Promise API提供的方法不是很多,有些有用的方法可以自己部署。下面介绍如何部署两个不在ES6之中、但很有用的方法。
Done()
Promise对象的回调链,无论是以then方法或者catch方法结尾,要是最后一个方法抛出错误,都有可能无法捕捉到(因为Promise内部的错误不会冒泡到全局)。因此我们可以提供一个done方法,总是处于回调链的尾端,保证抛出任何可能出现的错误。
asyncFunc()
.then()
.then()
.catch()
.done()
他的实现页很简单
Promise.prototype.done = function (onFulfilled, onRejected) {
this.then(onFulfilled, onRejected)
.catch(function (reason) {
// 抛出全局错误
setTimeout(() => {throw reason}, 0)
})
}
done方法的使用,可以像then方法那样用,提供Fulfilled和Rejected状态的回调函数,也可以不提供任何参数。但不管怎样,done都会捕捉到任何可能出现的错误,并向全局抛出。
finally()
finally方法不管状态是成功还是失败,都会执行的的操作,他与done的最大的区别,是他接受一个回调函数作为参数,该函数不管怎样都必须执行。
server.listen(0)
.then(function () {
// run test
})
.finally(server.stop);
实现
Promise.prototype.finally = function (callback) {
let P = this.cunstructor;
return this.then(function(value){
P.resolve(callback()).then(function(){
return value;
})
}, function(reason){
P.reject(callback()).then(function(){
throw reason;
})
})
}
上面代码中,不管前面的Promise是fulfilled还是rejected,都会执行回调函数callback。
