DEV Community

Discussion on: Async/await can still surprise you... A LOT!

Collapse
 
joelnet profile image
JavaScript Joel

Hello Charles,

I wanted to show a couple of additional ways of writing Sleep

First, you can use util.promisify on the setTimeout method:

const { promisify } = require('util');

const sleep = promisify(setTimeout);

(async () => {
  await sleep(1000);
  console.log('Hello');
})();

You can also use a function like this:

const sleep = timeout =>
  new Promise(resolve => setTimeout(resolve, timeout));

(async () => {
  await sleep(1000);
  console.log('Hello');
})();

Also, one neat thing I like to do is create a generic retry function. That way I can use it on any function that returns a Promise!

It would look something like this:

const serverMock = {
  count: 0,
  getData() {
    if (this.count === 2) {
      return Promise.resolve([{ name: "SomeName" }]);
    } else {
      this.count++;
      return Promise.reject("Error");
    }
  }
};

const retry = (attempts, action) => {
  const promise = action()
  return attempts > 0
    ? promise.catch(() => retry(attempts - 1, action))
    : promise
}

retry(2, () => serverMock.getData())

You can even do the same with the time limit feature!

Cheers! 🍻

Collapse
 
assuncaocharles profile image
Charles Assunção

Really nice Joel,

regarding the sleep/retry one amazing tool to make it even more simple is rxjs :D

learnrxjs.io/learn-rxjs/operators/...

Collapse
 
joelnet profile image
JavaScript Joel

Ahh the under appreciated rxjs. Such an amazing tool!