【发布时间】:2018-11-24 12:33:46
【问题描述】:
考虑以下代码示例,我将尝试通过两种方式获取结果,如果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 看起来更干净?
【问题讨论】:
-
你关心你使用哪个结果吗?例如你总是需要在 C 之前检查 A 先于 B 吗?
-
另外,只是好奇
async/await在某处引起了问题吗?切换到 Promise 链的动力是什么? -
async/await 语法的唯一原因是为了让事情看起来更干净(并且让 JS 新手更容易使用 Promise)。除了从单衬里移除大括号并可能将其变成单衬三元组之外,您无能为力让它看起来更干净。
-
@Hunter McMillen,是的。例如,如果 A 有效,则不再执行,否则尝试 B、C、D 等等。
-
Promise.any可能是一个答案,但实际上并不适合这种情况,因为它会触发所有方法。
标签: javascript ecmascript-6 promise async-await bluebird