考虑以下代码示例,我将尝试以两种方式获取结果,如果methodA
未给出预期结果,我将尝试methodB
。
function methodA () {
console.log('called A');
return Promise.resolve('not result');
}
function methodB () {
console.log('called B');
return Promise.resolve('result');
}
function isValid (result) {
return result === 'result';
}
async function getResult () {
let result = await methodA();
if (!isValid(result)) result = await methodB();
console.log('result', result);
}
我想使用传统的.then
样式来处理异步函数。
function getResult () {
return methodA()
.then((result) => {
if (isValid(result)) return result;
return methodB();
})
.then((result) => {
console.log('result', result);
});
}
我可能会在将来添加更多方法(methodC
,methodD
...)。
有没有办法让getResult
看起来更干净?
答案 0 :(得分:1)
您可以一个接一个地(按顺序)解决承诺:
function methodA() {
console.log('called A');
return Promise.resolve('not result');
}
function methodB() {
console.log('called B');
return Promise.resolve('result');
}
function methodC() {
console.log('called С');
return Promise.resolve('not result');
}
function getResult() {
let methods = [methodA, methodB, methodC];
let op = Promise.resolve();
methods.forEach(m => op = op.then(result => result == 'result' ? null : m()));
return op.then(() => console.log('result'));
}
getResult();

在上面的示例中,只会调用methodA
和methodB
。
答案 1 :(得分:0)
function methodA() {
console.log('called A');
return Promise.resolve('not result');
}
function methodB() {
console.log('called B');
return Promise.reject({ error: true, reason: 'idk' });
}
function methodC() {
console.log('called C');
return Promise.resolve('not result');
}
function methodD() {
console.log('called D');
return Promise.resolve('result');
}
function addFallback(promise, nextMethod) {
return promise
.then(result => result === 'result' ? result : nextMethod())
}
function getResult () {
let promise = methodA()
promise = addFallback(promise, methodB);
promise = addFallback(promise, methodC);
promise = addFallback(promise, methodD);
return promise
.then(result => {
if (result) { console.log('result', result); }
});
}
getResult()
.catch(e => { console.log(e)});
答案 2 :(得分:0)