Created
January 19, 2020 13:24
-
-
Save kombuchamp/f0cb7cb08731930e3dbeee84525df5b0 to your computer and use it in GitHub Desktop.
JS await pitfall
This file contains 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
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