loop async javascript
// Series loop
async (items) => {
for (let i = 0; i < items.length; i++) {
// for loop will wait for promise to resolve
const result = await db.get(items[i]);
console.log(result);
}
}
// Parallel loop
async (items) => {
let promises = [];
// all promises will be added to array in order
for (let i = 0; i < items.length; i++) {
promises.push(db.get(items[i]));
}
// Promise.all will await all promises in the array to resolve
// then it will itself resolve to an array of the results.
// results will be in order of the Promises passed,
// regardless of completion order
const results = await Promise.all(promises);
console.log(results);
}
function delay() {
return new Promise(resolve => setTimeout(resolve, 300));
}
async function delayedLog(item) {
// notice that we can await a function
// that returns a promise
await delay();
console.log(item);
}
async function processArray(array) {
array.forEach(async (item) => {
await delayedLog(item);
})
console.log('Done!');
}
processArray([1, 2, 3]);