Last active
April 20, 2017 11:06
-
-
Save ahmehri/ed6c49d7f6759271d02d91f4c5f40ef8 to your computer and use it in GitHub Desktop.
Usage of forEach with an array of promises is not a correct usage, Promise.all and for of should be used instead.
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
'use strict'; | |
import test from 'ava'; | |
let promise1; | |
let promise2; | |
let promise3; | |
let promises; | |
test.beforeEach(() => { | |
promise1 = new Promise(resolve => setTimeout(resolve, 500, 'fast')); | |
promise2 = new Promise(resolve => setTimeout(resolve, 300, 'faster')); | |
promise3 = new Promise(resolve => setTimeout(resolve, 50, 'fastest')); | |
promises = [promise1, promise2, promise3]; | |
}); | |
test('forEach with await', async () => { | |
// forEach returns undefined, hence await doesn't have any effect | |
await promises.forEach(async p => { | |
// the following await will only pause the parent fn (forEach callback) | |
const data = await p; | |
console.log(data); | |
}); | |
/* | |
this will be executed before the resolution of promises and the main fn | |
will exit -> promises won't be resolved | |
*/ | |
console.log('end'); // end | |
}); | |
test('Promise.all should be used when we want concurrent execution', | |
async () => { | |
const result = await Promise.all( | |
promises.map(async p => { | |
const data = await p; | |
console.log(data); | |
return data; | |
}) | |
); | |
console.log(result); // [ 'fast', 'faster', 'fastest' ] | |
console.log('end'); | |
/* | |
fastest | |
faster | |
fast | |
end | |
*/ | |
} | |
); | |
test('for of should be used when we want sequential execution', | |
async () => { | |
for (const p of promises) { | |
const data = await p; | |
console.log(data); | |
} | |
console.log('end'); | |
/* | |
fast | |
faster | |
fastest | |
end | |
*/ | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment