I have the following function that I want to return 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[];
}
}
Firstly I got "function lacks ending return statement and return type does not include 'undefined'"
And then I added undefined (so return type becomes Promise< number[] | undefined >)
But I'm getting "not all code paths return a value" this time.
It seems I'm not considering a possible code path with below code
Promise.all(...)
.then(val => {return ...})
What I'm missing?
I also tried this
Promise.all(...)
.then(val => {return ...})
.catch(e => {return ...})
But it was not helpful
Note: My main purpose is to return Promise< number[] >, not Promise< number[] | undefined >
Your branch with Promise.all
never issues a return (value)
statement. The then
callback does, but not the code outside the then
callback.
You probably want to return
the result of Promise.all().then()
.
return Promise.all(commentLines)
// ^^^^^^
.then(commitLines => {
return Array.prototype.concat.apply([], commitLines);
});