主要用于解决回调地狱的问题
// 传统写法
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中函数执行的返回值