Skip to content

Instantly share code, notes, and snippets.

@jstarry

jstarry/main.ts Secret

Created April 26, 2022 08:02
Show Gist options
  • Save jstarry/9b86287eec9468696d5dd28aa7a6c50a to your computer and use it in GitHub Desktop.
Save jstarry/9b86287eec9468696d5dd28aa7a6c50a to your computer and use it in GitHub Desktop.
NodeJS async race conditions
const fn2 = async (id: number) => {
console.log(`[${id}] called fn2`);
};
const fn = async (id: number) => {
console.log(`[${id}] fn start`);
await fn2(id);
console.log(`[${id}] fn end`);
};
(async () => {
await Promise.all(new Array(2).fill(0).map((async (_, id) => {
console.log(`[${id}] start`);
await fn(id);
console.log(`[${id}] finish`);
})));
})();
/*
Output:
[0] start
[0] fn start
[0] called fn2
[1] start
[1] fn start
[1] called fn2
[0] fn end
[1] fn end
[0] finish
[1] finish
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment