Skip to content

Instantly share code, notes, and snippets.

@saitergun
Last active June 24, 2024 09:35
Show Gist options
  • Save saitergun/d10f810fa6f2ac5a8d9aa9a8317f93b9 to your computer and use it in GitHub Desktop.
Save saitergun/d10f810fa6f2ac5a8d9aa9a8317f93b9 to your computer and use it in GitHub Desktop.
async for each
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