Skip to content

Instantly share code, notes, and snippets.

@ddialar
Last active August 25, 2017 04:15
Show Gist options
  • Save ddialar/c25916eb69835e41a964b2388d38d6ce to your computer and use it in GitHub Desktop.
Save ddialar/c25916eb69835e41a964b2388d38d6ce to your computer and use it in GitHub Desktop.
import log4js from './common/logger';
var logger = log4js.getLogger('app.js');
function performTask(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// this wont work as intended
// This code is not working as you spect because the 'forEach' function will never be
// able to return a promise.
// Due to that, if you run this code (with the logger trace after the addition operation),
// you will obtain that:
// [ INFO] - fn1 0
// [TRACE] - taskSum: 1
// [TRACE] - taskSum: 3
// [TRACE] - taskSum: 6
// [TRACE] - taskSum: 10
// [TRACE] - taskSum: 15
// [ INFO] - fn2 15
// As you can see, the forEach's 'await' is ignored, the final 'fn1' is printed and finally,
// once all forEach's internal async functions are completed, their results are shown.
async function asyncFn1() {
const someTasks = [1, 2, 3, 4, 5];
let taskSum = 0;
await someTasks.forEach(async t => {
await performTask(t);
taskSum += t;
logger.trace(`taskSum: ${taskSum}`);
});
logger.info('fn1', taskSum); // fn1 0
}
// This works as intended!
// This code works because the awaiting operation is been applied over an async
// function which is able to return a promise and not directly on the 'for' sentence.
// Due to that, the 'for' iteration flow is paused every time the 'async' function is run and
// this flow continues after that function's promise is resolved.
// Anyway, in order to work with async/await on iterations, it's recomended directly
// work with plain loops.
// Reference: https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop/37576787#37576787
async function asyncFn2() {
const someTasks = [1, 2, 3, 4, 5];
let taskSum = 0;
for (let t of someTasks) {
await performTask(t);
taskSum += t;
}
logger.info('fn2', taskSum); // fn2 15
}
asyncFn1();
asyncFn2();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment