Skip to content

Instantly share code, notes, and snippets.

@lastday154
Created June 4, 2018 14:15
Show Gist options
  • Select an option

  • Save lastday154/f4701dc782b6b069bbe6c23030ded48b to your computer and use it in GitHub Desktop.

Select an option

Save lastday154/f4701dc782b6b069bbe6c23030ded48b to your computer and use it in GitHub Desktop.
async/await loops
'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