Cem Kaan
Cem Kaan

Reputation: 2226

How to run forEach on a promise?

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

Answers (2)

Ali Nauman
Ali Nauman

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

D. Pardal
D. Pardal

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

Related Questions