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

时间:2018-06-14 16:51:50

标签: javascript ecmascript-6 promise async-await bluebird

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

3 个答案:

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




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

答案 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)