Delay execution (async emulation) Node.js

JS
S
JavaScript

2 solutions for moving call instructions to the bottom of the call stack. The event loop is what allows Node.js to perform non-blocking I/O operations. https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ Golden rule (to process long iterations without blocking the Event Loop): Partitioning the code too much is problematic and doing it too little can block for too long.

1// Delay with promise & setTimeOut
2const sleep = (time) => new Promise((resolve) => setTimeout(resolve, time));
3module.exports = async function () {
4  // wait a 1sec until the API server is UP!
5  await sleep(1000);
6};
7
8
9
10// Delay function 1
11function doAsyncTask(cb) {
12  setImmediate(cb);
13}
14
15/* Delay function 2
16nextTick() is part of asynchronous API, and it postpones operations
17to just before event loop is resumed (after the actual functions terminate)
18*/
19function doAsyncTask1(cb) {
20  process.nextTick(()=>{
21    cb();
22  });
23}
24
25doAsyncTask(() => console.log(message));
26doAsyncTask1(() => console.log(message));
27
28let message = 'Called';
29
30
31// ------------------------------------------------------------------------------------------------
32// Partitioning long-running synchronous code. 
33router.get('/immediate', async (req, res, next) => {
34
35  function immediatePromise() {
36    return new Promise((resolve) => {
37      setImmediate(() => resolve());
38    });
39  }
40  const hash = crypto.createHash('sha256');
41  for (let i = 0; i < 1000000; i++) {
42    hash.update(generateRandomString());
43    // introduce delay
44    await immediatePromise();
45  }
46  res.send(hash.digest('hex') + '\n');
47});
48

Created on 7/4/2018