Promise的三个重要概念及其关系:决议(resolve),完成(fulfill),拒绝(reject)
☺创建promise语法如下:
new Promise(function(resolve, reject) {});
♥Promise.prototype.catch(onRejected) 拒绝回调函数
var promise = new Promise((resolve, reject) => {
setTimeout(() => {
reject('failed');
}, 0);
});
var promise2 = promise.catch((reason) => {
console.log(reason);
return 'successed';
});
var promise3 = promise.catch((reason) => {
console.log(reason);
});
var promise4 = promise.catch((reason) => {
console.log(reason);
throw 'failed 2';
});
♥结果:
image.png♥链式调用
new Promise((resolve, reject) => {
setTimeout(()=>{
resolve('first success');
},0);
}).then((msg) => {
//msg为'first success'
return 'second success';
}).then((msg) => {
console.log(msg);
});
♥结果:
第一个then返回的promise最终是'second success'
第二个then返回的promise最终是'undefined'
该程序最终返回'second success'
image.png
♥错误处理
var promise = new Promise((resolve, reject) => {
add(); // 抛出异常
resolve('success'); //不执行
});
console.log(promise);
promise.catch((reason) => {
console.log(reason);
});
♥过程:执行add抛出异常,导致promise被拒绝,拒绝原因即抛出的异常,然后在执行catch方法注册的拒绝回调
♥结果:
image.png♥决议 完成 拒绝
var promise = new Promise((resolve, reject) => {
resolve(Promise.resolve('success'));
// resolve(Promise.reject('failed'));
});
promise.then((msg) => {
console.log(promise);
console.log('完成:' + msg);
}, (reason) => {
console.log(promise);
console.log('拒绝:' + reason);
});
♥结果:
image.png☺组合
Promise.resolve()
和 Promise.reject()
是手动创建一个已经 resolve 或者 reject 的 Promise 快捷方法。它们有时很有用。
Promise.all()
和 Promise.race()
是并行运行异步操作的两个组合式工具。
Promise.all([func1(), func2(), func3()])
.then(([result1, result2, result3]) => { /* use result1, result2 and result3 */ });
[func1, func2, func3].reduce((p, f) => p.then(f), Promise.resolve())
.then(result3 => { /* use result3 */ });
网友评论