将 async/await 样式转换为传统的 .then 样式



考虑下面的代码示例,我将尝试以两种方式获得结果,如果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);
});
}

将来我可能会添加更多方法(methodCmethodD...(。

有没有办法让getResult看起来更干净?

JSFiddle

您可以一个接一个地解决承诺(按顺序(:

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();

在上面的示例中,只会调用methodAmethodB

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)});

  • 看看 babel-plugin-transform-async-to-promise
  • 还有一个 PR 将其包含在核心中

最新更新