【问题标题】:Promise.all.then Not all code paths return a valuePromise.all.then 并非所有代码路径都返回值
【发布时间】:2019-05-26 22:55:16
【问题描述】:

我想要返回以下函数 Promise

async fetchCommentLines(commitDict: CommitDict): Promise < number[] > {
    if (GitCommentService.isLoggedIn()) {
        const commentLines = Object.values(commitDict).map(async commit => {
            // ...
            // do the job and return number[]
            // ...
            return lineNums;
        });

        Promise.all(commentLines)
            .then(commitLines => {
                return Array.prototype.concat.apply([], commitLines);
            });
    } else {
        return [] as number[];
    }
}

首先我得到“函数缺少结束返回语句并且返回类型不包括'undefined'”

然后我添加了 undefined (所以返回类型变为 Promise

但这次我得到“并非所有代码路径都返回值”

看来我没有考虑下面代码的可能代码路径

Promise.all(...)
.then(val => {return ...})

我错过了什么?

我也试过了

Promise.all(...)
.then(val => {return ...})
.catch(e => {return ...})

但是没用

注意:我的主要目的是返回Promise,而不是Promise

【问题讨论】:

    标签: javascript typescript promise async-await es6-promise


    【解决方案1】:

    您的带有Promise.all 的分支永远不会发出return (value) 语句。 then 回调可以,但不是then 回调之外的代码。

    您可能想要return Promise.all().then() 的结果。

        return Promise.all(commentLines)
    //  ^^^^^^
            .then(commitLines => {
                return Array.prototype.concat.apply([], commitLines);
            });
    

    【讨论】:

    • 我的目的是将number[][] 扁平化为number[] 所以[[1,2],[3,4]] 变为[1,2,3,4] 我会尝试你提到的其他方式
    • @user3790180 - 啊!那样的话,别理我。 :-)(我已经删除了答案的那一部分。)您可能会查看Array.prototype.flat。它处于第 3 阶段,并且已经被 Chrome 和 Firefox 支持,很容易为其他人填充... :-) 那将是 return Promise.all(commentLines).then(commitLines =&gt; commitLines.flat());
    【解决方案2】:

    你应该返回Promise

    return Promise.all(commentLines).then(...)
    //....
    

    或者等待promise并返回结果对象

    let lines = await Promise.all(commentLines)
    return [].concat(...lines)
    

    【讨论】:

      猜你喜欢
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2013-10-06
      • 2016-02-14
      • 2014-04-02
      相关资源
      最近更新 更多