Skip to content

Instantly share code, notes, and snippets.

@SamanShafigh
Last active October 30, 2018 23:45
Show Gist options
  • Save SamanShafigh/1ebd7339629bb0d0af7c7aba7e960e4b to your computer and use it in GitHub Desktop.
Save SamanShafigh/1ebd7339629bb0d0af7c7aba7e960e4b to your computer and use it in GitHub Desktop.
Asynchronous AntiPatterns
// :)
// Let say you can perform these 3 actions in parallel, then you can run them
// all at once and aggregate the result which is good
var p1 = addB(2, 3)
var p2 = addB(2, 3)
var p3 = addB(2, 3)
Promise.all([p1, p2, p3]).then(([r1, r2, r3]) => {
console.log(r1, r2, r3)
})
// :(
// However if you do this it means you running them one after another so do not
// abuse async/await. So I think async/await in this way is much more easier to be abused
async function main () {
var r1 = await addB(2, 3);
var r2 = await addB(2, 3);
var r3 = await addB(2, 3);
console.log(r1, r2, r3)
}
// :(
// Although the above code is exactly same as this which is bad too (note that we
// assume you can perform the following actions in parallel)
var r1;
var r2;
var r3;
addB(2, 3)
.then(result => {
r1 = result;
return addB(2, 3);
})
.then(result => {
r2 = result;
return addB(2, 3);
})
.then(result => {
r3 = result;
})
.then(() => {
console.log(r1, r2, r3)
})
// :( :(
// Even worse than above code is to implement a nested promise so I don't
// know why somebody do something like this
addB(2, 3)
.then(result => {
r1 = result;
addB(2, 3).then(result => {
r2 = result;
addB(2, 3).then(result => {
r3 = result;
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment