Created
June 4, 2018 14:15
-
-
Save lastday154/f4701dc782b6b069bbe6c23030ded48b to your computer and use it in GitHub Desktop.
async/await loops
This file contains hidden or 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'; | |
| const delay = () => new Promise((resolve) => setTimeout(resolve, 300)); | |
| const delayedLog = async (item) => { | |
| await delay(); | |
| console.log(item); | |
| }; | |
| const processArray = (array) => { | |
| array.forEach(async (item) => { | |
| await delayedLog(item); | |
| }); | |
| console.log('done'); | |
| }; | |
| const processArray1 = async (array) => { | |
| for (const item of array) { | |
| await delayedLog(item); | |
| } | |
| console.log('done'); | |
| }; | |
| const processArray2 = async (array) => { | |
| const promises = array.map(delayedLog); | |
| await Promise.all(promises); | |
| console.log('done'); | |
| }; | |
| processArray([1, 2, 3]); | |
| /* | |
| done | |
| 1 | |
| 2 | |
| 3 | |
| */ | |
| processArray1([1, 2, 3]); | |
| /* | |
| 1 | |
| 2 | |
| 3 | |
| done | |
| */ | |
| processArray2([1, 2, 3]); // fastest | |
| /* | |
| 1 | |
| 2 | |
| 3 | |
| done | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment