Skip to content

Instantly share code, notes, and snippets.

@kombuchamp
Created January 19, 2020 13:24
Show Gist options
  • Save kombuchamp/f0cb7cb08731930e3dbeee84525df5b0 to your computer and use it in GitHub Desktop.
Save kombuchamp/f0cb7cb08731930e3dbeee84525df5b0 to your computer and use it in GitHub Desktop.
JS await pitfall
let result = 0;
const sleep = (ms) => new Promise((resolve)=>{
setTimeout(resolve, ms);
});
const mult = async(val) => {
await sleep(200);
return val * val;
}
const add = async(val)=>{
result += await mult(val);
}
Promise.all([
add(2),
add(1),
]).then(()=>{
console.log(result); // prints 1
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment