Promise的含义
Promise是异步编程的一种解决方案,比传统的回调函数和事件方式更合理和更强大。ES6将其写进语言标准,统一用法,原生提供Promise对象。
Promise对象的两个特点
(1)对象的状态不受外界影响。
Promise对象有三种状态,只由异步操作的结果决定:Pending(进行中)、Resolved(已完成,又称Fulfilled)和Rejected(已失败)。
(2)一旦状态改变,就不会再变,任何时候都可以得到这个结果。
Promise对象只有两种状态改变:从Pending变为Resolved或Rejected,状态改变就会固定,并会一直保持这个结果,对该Promise对象添加回调函数,也会得到结果。如果错过了事件,再去监听,是得不到结果的。
新建Promise的对象会立即执行,无法中途取消。
不设置回调函数,Promise内部抛出的错误,不会反应到外部。
Pending状态时,无法得知当前阶段(刚刚开始还是即将完成)。
基本用法
ES6规定,Promise对象是一个构造函数,用来生成Promise实例。
下面代码创造了一个Promise实例。
var promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 异步操作成功 */){
// 从Pending变为Resolved
resolve(value);
} else {
// 从Pending变为Rejected
reject(error);
}
});
Promise实例创建后,then方法接受Resolved状态和Reject状态的回调函数,第二个参数可选。
promise.then(function(value) {
// success
}, function(error) {
// failure
});
下面是一个Promise对象的简单例子。
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms, 'done');
});
}
timeout(100).then((value) => {
console.log(value);
});
上面代码中,timeout方法返回Promise实例,该实例ms
毫秒后状态变为Resolved,并且触发then方法绑定的回调函数。
Promise新建后就会立即执行。
let promise = new Promise(function(resolve, reject) {
console.log('Promise');
resolve();
});
promise.then(function() {
console.log('Resolved.');
});
console.log('Hi!');
// Promise
// Hi!
// Resolved
上面的Promise新建后立即执行,所以首先输出“Promise”。然后,当前脚本所有同步任务执行完才会执行指定的then方法的回调 ,所以“Resolved”最后输出。
下面是异步加载图片的例子。
function loadImageAsync(url) {
return new Promise(function(resolve, reject) {
var image = new Image();
image.onload = function() {
resolve(image);
};
image.onerror = function() {
reject(new Error('Could not load image at ' + url));
};
image.src = url;
});
}
上面代码中,使用Promise包装了一个图片加载的异步操作。如果加载成功,就调用resolve方法,否则就调用reject方法。
调用resolve函数和reject函数时的参数会传递给回调函数。
reject函数的参数通常是Error对象的实例;resolve函数的参数除了正常的值以外,还可能是另一个Promise实例,比如像下面这样。
var p1 = new Promise(function (resolve, reject) {
// ...
});
var p2 = new Promise(function (resolve, reject) {
// ...
resolve(p1);
})
上面代码中,p1和p2都是Promise的实例,但是p2的resolve方法将p1作为参数,即一个异步操作的结果是返回另一个异步操作。p1的状态就会传递给p2,即p1的状态决定了p2的状态。p2的回调函数在p1的状态改变后执行。
var p1 = new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('fail')), 3000)
})
var p2 = new Promise(function (resolve, reject) {
setTimeout(() => resolve(p1), 1000)
})
p2
.then(result => console.log(result))
.catch(error => console.log(error))
// Error: fail
p13秒之后变为rejected,p2的状态在1秒之后改变,resolve方法返回的是p1,由于p2返回的是另一个Promise,所以后面的then语句都针对(p1)。又过了2秒,p1变为rejected,导致触发catch方法指定的回调函数。
Promise.prototype.then()
then方法定义在原型对象Promise.prototype上,为Promise实例添加状态改变时的回调函数。then方法的第一个参数是Resolved状态的回调函数,第二个参数(可选)是Rejected状态的回调函数。then方法返回值是一个新的Promise实例,因此可进行链式操作,可以用来顺序操作异步方法。
getJSON("/post/1.json").then(function(post) {
return getJSON(post.commentURL);
}).then(function funcA(comments) {
console.log("Resolved: ", comments);
}, function funcB(err){
console.log("Rejected: ", err);
});
Promise.prototype.catch()
Promise.prototype.catch方法是.then(null, 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));
下面是一个例子。
var promise = new Promise(function(resolve, reject) {
throw new Error('test');
});
promise.catch(function(error) {
console.log(error);
});
// Error: test
上面代码中,上面的写法与下面两种写法是等价的。
// 写法一
var promise = new Promise(function(resolve, reject) {
try {
throw new Error('test');
} catch(e) {
reject(e);
}
});
promise.catch(function(error) {
console.log(error);
});
// 写法二
var promise = new Promise(function(resolve, reject) {
reject(new Error('test'));
});
promise.catch(function(error) {
console.log(error);
});
比较上面两种写法,reject方法的作用等同于抛出错误。
如果Promise状态已经变成Resolved后的抛错不会被抛出,等于无效。
var promise = new Promise(function(resolve, reject) {
resolve('ok');
throw new Error('test');
});
promise
.then(function(value) { console.log(value) })
.catch(function(error) { console.log(error) });
// ok
Promise对象的错误具有“冒泡”性质,会一直向后传递,直到被捕获为止。
跟传统的try/catch代码块不同的是,如果不指定catch回调函数,Promise对象抛出的错误不会传递到外层代码,即不会有任何反应。
下面代码中,someAsyncThing函数产生的Promise对象会报错,但是由于没有指定catch方法,这个错误不会被捕获,也不会传递到外层代码,导致运行后没有任何输出。注意,Chrome浏览器不遵守这条规定,它会抛出错误“ReferenceError: x is not defined”。
var someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行会报错,因为x没有声明
resolve(x + 2);
});
};
someAsyncThing().then(function() {
console.log('everything is great');
});
下面代码中,Promise指定在下一轮“事件循环”再抛出错误,结果由于没有指定使用try...catch语句,就冒泡到最外层,成了未捕获的错误。因为此时,Promise的函数体已经运行结束了,所以这个错误是在Promise函数体外抛出的。
var promise = new Promise(function(resolve, reject) {
resolve("ok");
setTimeout(function() { throw new Error('test') }, 0)
});
promise.then(function(value) { console.log(value) });
// ok
// Uncaught Error: test
Node.js有一个unhandledRejection事件,专门监听未捕获的reject错误。
process.on('unhandledRejection', function (err, p) {
console.error(err.stack)
});
上面代码中,unhandledRejection事件的监听函数有两个参数,第一个是错误对象,第二个是报错的Promise实例,它可以用来了解发生错误的环境信息。
需要注意的是,catch方法的返回值也是一个新的Promise对象。
catch方法之中,能再抛出错误。
var someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行会报错,因为x没有声明
resolve(x + 2);
});
};
someAsyncThing().then(function() {
return someOtherAsyncThing();
}).catch(function(error) {
console.log('oh no', error);
// 下面一行会报错,因为y没有声明
y + 2;
}).then(function() {
console.log('carry on');
});
// oh no [ReferenceError: x is not defined]
上面代码中,catch方法抛出一个错误,因为后面没有别的catch方法了,导致这个错误不会被捕获,也不会传递到外层。如果改写一下,结果就不一样了。
someAsyncThing().then(function() {
return someOtherAsyncThing();
}).catch(function(error) {
console.log('oh no', error);
// 下面一行会报错,因为y没有声明
y + 2;
}).catch(function(error) {
console.log('carry on', error);
});
// oh no [ReferenceError: x is not defined]
// carry on [ReferenceError: y is not defined]
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的执行结果决定。
(1)只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数。
(2)只要p1、p2、p3之中只要有一个被rejected,p的状态就变成rejected,且第一个被reject的实例的返回值,会传递给p的回调函数。
Promise.race()
Promise.race方法也是将多个Promise实例,包装成一个新的Promise实例。
var p = Promise.race([p1, p2, p3]);
上面代码中,p的状态取决于第一个改变状态的实例。最先改变的 Promise 实例的返回值会传递给p的回调函数。
Promise.race方法的参数与Promise.all方法一样,如果不是 Promise 实例,会Promise.resolve方法,将参数转为 Promise 实例,再进一步处理。
下面是一个例子,如果指定时间内没有返回结果,就将Promise的状态变为reject,否则变为resolve。
var p = Promise.race([
fetch('/resource-that-may-take-a-while'),
new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('request timeout')), 5000)
})
])
p.then(response => console.log(response))
p.catch(error => console.log(error))
Promise.resolve()
Promise.resolve将现有对象转为Promise对象.
Promise.resolve等价于下面的写法。
Promise.resolve('foo')
// 等价于
new Promise(resolve => resolve('foo'))
Promise.resolve方法的参数分成四种情况。
(1)参数是一个Promise实例,则返回这个实例。
(2)参数是一个thenable对象thenable对象指的是具有then方法的对象,比如:
let thenable = { then: function(resolve, reject) { resolve(42); } };
Promise.resolve方法会将这个对象转为Promise对象,并立即执行thenable对象的then方法。
then: function(resolve, reject) { resolve(42); } }; let p1 = Promise.resolve(thenable); p1.then(function(value) { console.log(value); // 42 });
(3)参数不是具有then方法的对象,或根本就不是对象,则Promise.resolve方法返回一个新的Promise对象,状态为Resolved。
var p = Promise.resolve('Hello'); p.then(function (s){ console.log(s) }); // Hello
(4)不带有任何参数,则直接返回一个Resolved状态的Promise对象。
需要注意的是,立即resolve的Promise对象,在本轮“事件循环”(event loop)的结束>时执行,而非下一轮“事件循环”的开始时。
setTimeout(function () { console.log('three'); }, 0); Promise.resolve().then(function () { console.log('two'); }); console.log('one'); // one // two // three
Promise.reject()
Promise.reject(reason)方法返回状态为rejectedPromise实例。它的参数用法与Promise.resolve方法完全一致。
finally()
finally方法用于指定不管Promise对象最后状态如何,都会执行的操作。
server.listen(0)
.then(function () {
// run test
})
.finally(server.stop);
它的实现如下:
Promise.prototype.finally = function (callback) { let P = this.constructor; return this.then( value => P.resolve(callback()).then(() => value), reason => P.resolve(callback()).then(() => { throw reason }) ); };
参考:ES6 promise对象