Thursday, January 23, 2020

My current favourite trick in Node.js

At my current job I need to work a lot with Node.js backend services, and one thing is recurring - I need to simulate some delays in the code, mostly for testing purposes.
In the old days this was pretty problematic, we had the classic "callback hell", which made the code very unreadable, sometimes had to refactor (copy-paste mostly) huge parts of the codebase, just to simulate some delay.
Nowadays the air is more fresh regarding asynchronous programming in the JavaScript economy, because we have Promises supported natively, and in newer versions of Node.js you get async-await, which we learned about in one of my previous posts (don't get fooled, the post is about the package `co`, which was essentially the equivalent of today's async-await).
So how do we simulate delays today? It's super easy actually, you just need to know that async-await is basically operating on top of Promises. Without any further discussion, here is the code:

await new Promise(resolve => setTimeout(resolve, 5000));

Let's look at what this codesnippet does.
await is going to wait (no pun intended) for a Promise, and until it resolves, it's not going to continue the execution flow.
So we create the Promise, where we just wait using the setTimeout method 5000 milliseconds (5s), and then resolve the Promise! Simple as that!
I think this is a pretty handy codesnippet, that I wish I knew before!

2 comments:

  1. const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
    ...
    await delay(5000);

    ReplyDelete
    Replies
    1. Haha, true! Thanks for the comment!
      I'm just usually too lazy to declare the function when debugging - I'm usually just copy-pasting the code :P

      Delete