Reputation: 2226
I have a function returning a promise of array async function functionReturningPromiseOfUserIDs(): Promise<string[]>
Is it possible to run forEach on returning array?
async function runForEachUser() {
await functionReturningPromiseOfUserIDs().forEach((userID: string) => {
return userID; // do stuff with userID
}
}
Typescript says:
Property 'forEach' does not exist on type '() => Promise<string[]>'.ts(2339)
Upvotes: 0
Views: 501
Reputation: 1677
You need to await the Promise returned by functionReturningPromiseOfUserIDs(). If you update your first line to be this
const userIds = await functionReturningPromiseOfUserIDs();
,
userIds will be the array of UserIds. Then you can simply use userIds.forEach((id) => {})
to do what you want with them,
Upvotes: 1
Reputation: 6587
When you write
async function runForEachUser() {
await functionReturningPromiseOfUserIDs().forEach((userID: string) => {
return userID;
});
}
Typescript thinks you're trying to call .forEach()
on the promise returned by functionReturningPromiseOfUserIDs()
. If you want to call .forEach()
on the value the promise resolves to, use this:
async function runForEachUser() {
(await functionReturningPromiseOfUserIDs()).forEach((userID: string) => {
return userID;
});
}
Also, .forEach()
ignores the return value of the callback.
Upvotes: 1