我有以下函数,我想返回 Promise<number[]>
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[];
}
}
首先我得到"函数缺少结束返回语句,返回类型不包括'未定义'"
然后我添加了未定义(因此返回类型变为 Promise<number[]>)
但是这次我得到"并非所有代码路径都返回值"。
似乎我没有考虑使用以下代码的可能代码路径
Promise.all(...)
.then(val => {return ...})
我错过了什么?
我也试过这个
Promise.all(...)
.then(val => {return ...})
.catch(e => {return ...})
但这没有帮助
注意:我的主要目的是返回 Promise<number[]>,而不是 Promise<number[]>
具有 Promise.all
的分支从不发出return (value)
语句。then
回调会,但then
回调之外的代码不会。
您可能想return
Promise.all().then()
的结果。
return Promise.all(commentLines)
// ^^^^^^
.then(commitLines => {
return Array.prototype.concat.apply([], commitLines);
});
您应该返回Promise
return Promise.all(commentLines).then(...)
//....
或等待 promise 并返回结果对象
let lines = await Promise.all(commentLines)
return [].concat(...lines)