如果没有嵌套在初始promises then语句中,如果前面的promise没有解析,那么推销promise系列的推荐方法是什么,以便后续的promises不运行?
如果承诺1无法解决,我不想运行承诺2。
var promise1 = new Promise((resolve, reject) =>{
reject('catch 1')
});
var promise2 = new Promise((resolve, reject) =>{
resolve('pass 2')
});
我想这样做:
var p1Resolved = promise1.then(result=>{
handleResult(result);
})
.catch(error => {
handleError(error);
})
if(p1Resolved)
{
promise2.then(result=>{
handleResult(result);
})
.catch(error => {
handleError(error);
})
}
我不想这样做(然后在promise1里面嵌套promise2):
promise1.then(result=>{
promise2.then(result=>{
handleResult(result);
})
.catch(error => {
handleError(error);
})
})
.catch(error => {
handleError(error);
})
答案 0 :(得分:1)
将promise2转换为函数(为了保持一致性,也可以将promise1转换为
)
var promise1 = () => new Promise((resolve, reject) => reject('catch 1'));
var promise2 = () => new Promise((resolve, reject) => resolve('pass 2'));
promise1()
.then(result => promise2())
.then(result => console.log('done'))
.catch(reason => console.log('error', reason));