主要用于解决回调地狱的问题
// 传统写法
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// ...
});
});
});
});
// Promise 的写法
(new Promise(step1))
.then(step2)
.then(step3)
.then(step4);
var promise = new Promise(function (resolve, reject) {
// ...
if (/* 异步操作成功 */){
resolve(value);
} else { /* 异步操作失败 */
reject(new Error());
}
});
.then(successCallback, failureCallback)
在Promise中:如果不调用resolve或reject,状态将一直保持在pending
在then中:只要不抛出错误,函数正常执行后状态也会变为fulfilled,继续链式执行
somePromiseThatRejects
.then(null,
(error) => {
console.error('I tried but failed:', error);
throw new Error('I cannot handle this!'); // 或者 return Promise.reject(...)
}
)
.then(
(value) => { console.log('Success'); }, // 这里不会执行
(error) => { console.error('Chain still broken:', error); } // 这里会执行
);
传入给下一个then中的参数是这个then中函数执行的返回值
该方法是.then(null, rejection) 或.then(undefined, rejection) 的别名,用于指定发生错误时的回调函数
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));
注意:Promise对象错误具有冒泡属性,会一直向后传递,直到被捕获为止。
getJSON('/post/1.json').then(function(post) {
return getJSON(post.commentURL);
}).then(function(comments) {
// some code
}).catch(function(error) {
// 处理前面三个Promise产生的错误
});
该方法用于指定不管Promise对象最后状态如何,都会执行的操作
promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···})
该方法用于多个Promise实例,包装成一个新的Promise实例
const p = Promise.all([p1, p2, p3])
p的状态由p1 p2 p3决定
p1 p2 p3 的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1 p2 p3的返回值组成一个数组,传递给p的回调函数p1 p2 p3 之中有一个被rejected ,p 的状态就变成rejected ,此时第一个被reject 的实例的返回值,会传递给p 的回调函数