怎么能避免这个小小的回调地狱?这段代码工作正常
estaElServicioDespachado(15).then(function(){
sePermiteModificarElCupon(25).then(function(respuesta){
$state.go("barra.general.formularioCupon");
},function(error){
alert(error);
})
},
function(error){
alert(error);
});
我试图做这样的事情以避免回调地狱,但当'sepermitemodificarElcupon'拒绝
时,没有调用catch函数 estaElServicioDespachado(15)
.then(sePermiteModificarElCupon(25)}
.then(function(){$state.go("barra.general.formularioCupon");})
)
.catch(function(error){
alert(error);
})
也许这会有所帮助。这是调用返回promises的服务函数的函数
function estaElServicioDespachado (id_servicio){
return catalogoServicios.estaElServicioDespachado(id_servicio)
}
function sePermiteModificarElCupon(id_cupon){
return catalogoCupones.sePermiteModificarElCupon(id_cupon);
}
答案 0 :(得分:1)
您正在寻找的词是:Promise.all()
将你的承诺链接起来:
var promise1 = estaElServicioDespachado(15)
var promise2 = sePermiteModificarElCupon(25)
Promise.all([promise1, promise2])
.then(function(){$state.go("barra.general.formularioCupon");})
.catch(reason => {
console.log(reason)
})
来自MDN的例子(添加了被拒绝的捕获承诺):
let promise1 = Promise.resolve(3);
let promise2 = new Promise(function(resolve, reject) {
setTimeout(resolve, 1000, 'foo');
});
let promise3 = 42;
let promise4 = Promise.reject('something went wrong in 4th promise');
// all goes well
Promise.all([promise1, promise2, promise3])
.then(function(values) {
console.log(JSON.stringify(values));
})
.catch((err) => { console.log(err) });
// an error thrown in the middle
Promise.all([promise1, promise2, promise4, promise3])
.then(function(values) {
console.log(JSON.stringify(values));
})
.catch((err) => { console.log(err) });