代码之家  ›  专栏  ›  技术社区  ›  kit

将async/await样式转换为传统样式。

  •  1
  • kit  · 技术社区  · 8 年前

    考虑下面的代码示例,如果 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 看起来更干净?

    JSFiddle

    3 回复  |  直到 8 年前
        1
  •  1
  •   alexmac    8 年前

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

    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 将被调用。

        2
  •  0
  •   Doug Coburn    8 年前

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