Last active
June 24, 2024 09:35
-
-
Save saitergun/d10f810fa6f2ac5a8d9aa9a8317f93b9 to your computer and use it in GitHub Desktop.
async for each
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function asyncForEach<T>( | |
array: Array<T>, | |
callbackfn: { | |
(value: T, index: number, array: T[]): Promise<void> | void; | |
} | |
) { | |
for (let index = 0; index < array.length; index++) { | |
await callbackfn(array[index], index, array); | |
} | |
} | |
type User = { | |
id: number; | |
name: string; | |
active: boolean; | |
birthday: Date; | |
}; | |
const users: User[] = [ | |
{ id: 1, name: "Sait", active: true, birthday: new Date("1990-01-03") }, | |
{ id: 2, name: "Ali", active: false, birthday: new Date("1995-05-11") }, | |
{ id: 3, name: "Veli", active: false, birthday: new Date("2000-10-22") }, | |
]; | |
// usage | |
(async () => { | |
await asyncForEach(users, async (user) => { | |
await new Promise((r) => setTimeout(r, 1000)); | |
console.log("user", user.birthday.toISOString()); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment