1const dummyfunction = async () => {
2 for (item of items) {
3 // Until promise returns,
4 // The loop waits here!
5 await turtle();
6 }
7}
1// Series loop
2async (items) => {
3 for (let i = 0; i < items.length; i++) {
4
5 // for loop will wait for promise to resolve
6 const result = await db.get(items[i]);
7 console.log(result);
8 }
9}
10
11// Parallel loop
12async (items) => {
13 let promises = [];
14
15 // all promises will be added to array in order
16 for (let i = 0; i < items.length; i++) {
17 promises.push(db.get(items[i]));
18 }
19
20 // Promise.all will await all promises in the array to resolve
21 // then it will itself resolve to an array of the results.
22 // results will be in order of the Promises passed,
23 // regardless of completion order
24
25 const results = await Promise.all(promises);
26 console.log(results);
27}
1async function processArray(array) {
2 // map array to promises
3 const promises = array.map(delayedLog);
4 // wait until all promises are resolved
5 await Promise.all(promises);
6 console.log('Done!');
7}
1const mapLoop = async _ => {
2 console.log('Start')
3
4 const numFruits = await fruitsToGet.map(async fruit => {
5 const numFruit = await getNumFruit(fruit)
6 return numFruit
7 })
8
9 console.log(numFruits)
10
11 console.log('End')
12}
13