假设函数返回自定义承诺。为了这个例子,我们假设需要一个自定义的承诺:
(注意:环境是AngularJS [即1.x]做ES5)
function doMyFunction() {
var d = $q.defer();
do1()
.then (function () { return do2(); }) //P1
.then (function () { return do3(); }) // P2
.then {function () {console.log ("All good"); d.resolve(true); return d.promise;}) // P3
.catch (function () {
console.log ("Oh no");
fallback1()
.then (function () {
console.log ("Ah this fallback1 worked");
d.resolve(true);
return d.promise;
}, function () {
console.log ("Oh no, fallback failed, do I have to go through nested hell to now try fallback 2?");
d.resolve(false);
return d.promise;
});
return d.promise;
}
如上所述,我试图按顺序尝试不同的方法,只有前一种方法失败。
如果我试着像这样压扁它:
// lets start from the last promise above
.then {function () {console.log ("All good"); d.resolve(true); return d.promise;}) // P3
.catch (function () { return fallback1(); })
.then (function () { d.resolve(true); return d.promise; }) // P4
.catch (function () {})
这不起作用,因为P3也会在P3成功时执行。
处理我需要按顺序尝试多个基于promise的函数的情况有什么好的方法,只有在前一个函数失败的情况下?
另外,我不确定我是否真的可以.then().catch().then().catch()
在这种情况下,是否有一种干净的方法可以避免地狱?
答案 0 :(得分:1)
您可以链接catch
方法调用,因为catch
也会返回可以解析或拒绝的承诺。因此,您实际上会在catch
回调中执行下一个回退:
function perform(i) { // Some mock function for this demo returning a promise
return new Promise((resolve, reject) => {
console.log('try with ' + i);
setTimeout(() => {
if (i < 4) reject("some error"); else resolve(i);
}, 100);
});
}
function doMyFunction() {
return perform(1)
.catch( () => perform(2) )
.catch( () => perform(3) )
.catch( () => perform(4) ) // <-- this is the first one that resolves
.catch( () => perform(5) ) // <-- this callback is never executed
.catch( () => perform(6) ); // <-- (idem)
}
doMyFunction().then( (i) => console.log('Success with step ' + i) ); // <-- final result
&#13;
请注意,使用AngularJS下的ES5代码,第一个模拟函数将如下所示:
function perform(i) { // Some function returning a promise
var d = q$.defer();
console.log('try with ' + i);
setTimeout(() => {
if (i < 4) d.reject("some error"); else d.resolve(i);
}, 100);
return d.promise();
}
如果您的逻辑中间有其他处理程序,您可以在函数中使用上述原则,只需调用该函数即可为其提供所有可能的回退:
function perform(i) { // Some mock function for this demo returning a promise
return new Promise((resolve, reject) => {
console.log('try with ' + i);
setTimeout(() => {
if (i < 4) reject("some error"); else resolve(i);
}, 100);
});
}
function tryAndFallback(fallbacks) {
return (function loop(fallbacks) {
if (!fallbacks.length) return Promise.reject("Nothing worked!");
return fallbacks[0]().catch( () => loop(fallbacks.slice(1)) );
})(fallbacks);
}
function doMyFunction() {
return Promise.resolve() // <-- some promise that is just fine
// Now a task that has a few fallbacks
.then( () => tryAndFallback([() => perform(2),
() => perform(3),
() => perform(4)]) )
.then( () => console.log('more work can be done here') );
}
doMyFunction().then( (i) => console.log('All done') ); // <-- final result
&#13;
答案 1 :(得分:0)
您是否考虑过异步/等待javascript? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
验证浏览器兼容性是否可接受。
async function() {
let first, second, third, fourth;
try {
first = await do1();
second = await do2();
third = await do3();
fourth = await do4();
return fourth;
} catch(e){
console.log(e + ' failed. Reverting back to the first')
}
return first;
}
我不知道。未经测试,但由于它们都未定义,如果您只想返回最后接受的项目,那么您可以在捕获后测试以下最终返回:
return fourth || third || second || first;
它应该只返回第一个有效结果,这个结果是具有可接受值的最终结果。
答案 2 :(得分:-1)
正确的承诺链接应该如下所示
function doWholeWork(){
return work1().
then((work1Result)=>{
return work2();
})
then((work2Result)=>{
return work3();
})
.catch(error=>{
console.log("Some error happened", error)
});
}