I've spent the last two weeks learning about the following: setImmediate, process.nextTick, setTimeout, promises, callbacks, libuv, the event loop, job/microtask queue, event loop queue, call stacks, etc.
I've truly gone down a rabbit hole that I can't escape and while I find myself a lot more informed, I'm still have trouble grasping async code in JavaScript.
I'd like to take the following basic scenario and understand how I might implement it async.:
// does nothing; here to simulate functionality below
var data = new Array(10000000);
const displayTime = desc => {
var time = new Date();
console.log(
("0" + time.getHours()).slice(-2) + ":" +
("0" + time.getMinutes()).slice(-2) + ":" +
("0" + time.getSeconds()).slice(-2) + " " + desc
);
}
displayTime('starting ...');
// --- async/await (a promise):
const processData = async(data) => {
let dataLen = data.length;
let processedData = [];
//console.time('#1');
for (let ctr = 0; ctr < dataLen; ctr++) {
// something happens here; simulating a long task using a for-loop;
// for purposes of this question, let's just assume it's necessary to do this
processedData.push(ctr / 33 * 383739722);
}
//console.timeEnd('#1');
return processedData;
}
(async() => {
result = await processData(data);
// console.log(result);
displayTime('#1 completed ...');
})();
// --- promise:
const processData2 = data => {
return new Promise((resolve, reject) => {
let dataLen = data.length;
let processedData = [];
//console.time('#2');
for (let ctr = 0; ctr < dataLen; ctr++) {
processedData.push(ctr / 33 * 383739722);
}
//console.timeEnd('#2');
resolve(processedData)
});
}
processData2(data).then(data => {
// console.log(data);
displayTime('#2 completed ...');
});
displayTime('end of program ...');
Output is:
18:09:48 starting ...
18:09:52 end of program ...
18:09:52 #1 completed ...
18:09:52 #2 completed ...
As you can see from the output, "end of program ..." wasn't echoed to the screen until after the two long running processes completed (see time).
Why?
How could I have run these two tasks (which both use promises) in the background so that they don't block the event loop and my "end of program ..." string echo immediately?
async
doesn't make it run asynchronously. It's just syntactic sugar for returning a promise, which makes it easier to use if it executes asynchronous code, and allows it to useawait
internally to call other async functions.setTimeout
.setTimeout
executes its callback function asynchronously.starting
message and an error screen. Did you copy it correctly?