【问题标题】:Return from a Promise.all doesn't return from the wrapping function从 Promise.all 返回不会从包装函数返回
【发布时间】:2019-02-04 01:37:41
【问题描述】:

如果 Promise.all 解决后满足某些条件,我想从函数返回。但是return语句似乎没有效果,函数继续执行。

这是我的代码:

function somefunc() {

    Promise.all([match2, match3, match4, match5]).then(results => {
        console.log(results);
        if(results.indexOf(false) > -1) {
            return; // has no effect. somefunc() does NOT return. 
        }
        else {
            // ............
        };

    }).catch(err => {
      console.log(err);
    });

    // this continues to get executed even after the return staement
}

【问题讨论】:

    标签: javascript node.js promise


    【解决方案1】:

    如果你想返回它的 Promise 链中的某些东西,你必须返回 Promise.all

    function somefunc() {
    
        return Promise.all([match2, match3, match4, match5]).then(results => {
            console.log(results);
            if(results.indexOf(false) > -1) {
                return; // has an effect. somefunc() will return. 
            }
            else {
                // ............
            };
    
        }).catch(err => {
          console.log(err);
        });
    
        // this will not get executed after the return staement
    }
    

    【讨论】:

    • 我将return 添加到Promise.all 但promise 之后的代码确实会继续执行。
    【解决方案2】:

    Promise.all([ 是异步解析,因此// this continues to get executed even after the return staement 将始终在then 中的代码运行之前执行。

    您必须使用await/async:

    async function somefunc() {
      try {
        var results = await Promise.all([match2, match3, match4, match5]);
    
        if (results.indexOf(false) > -1) {
          return;
        } else {
          // ............
        };
      } catch (err) {
        console.log(err);
      }
    
      // code that is executed if return is not done
    }
    

    或者你需要在 then 中移动 // this continues to get executed even after the return staement 的代码,你应该将 Promise 链 return 形成你的函数,这样如果有人调用 somefunc 就可以等待函数完成:

    function somefunc() {
    
      return Promise.all([match2, match3, match4, match5]).then(results => {
        console.log(results);
        if (results.indexOf(false) > -1) {
          return; // has no effect. somefunc() does NOT return. 
        } else {
          // ............
        };
    
        // code that is executed if return is not done
      }).catch(err => {
        console.log(err);
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多