Neues Node.js-Buch
Alle Artikel

Create a delaying function in promise-style

Problem

You want to create a function that creates a promise that delays for a given number of milliseconds.

Ingredients

  • a function
  • the Promise object
  • the setTimeout() function

Directions

  1. Create a function that accepts the number of milliseconds.

    function delay(ms) {
      ...
    }
  1. Let the function return a promise object.

    function delay(ms) {
      return new Promise(...);
    }
  2. Add the resolve-/reject-callback to the promise.

    function delay(ms) {
      return new Promise(
        (resolve, reject) => {
          ...
        }
      );
    }
  3. Inside that callback function call setTimeout().

    function delay(ms) {
      return new Promise(
        (resolve, reject) => {
          setTimeout(resolve, ms);
        }
      );
    }
  4. Voilá, a perfect delaying function in promise-style.

    delay(5000).then(() => {
      console.log('Printed after 5 seconds.')
    });

Variants

  • If you want to pass data to the promise:

    function delay(ms, data) {
      return new Promise(
        (resolve, reject) => {
          setTimeout(() => {
            resolve(data);
          }, ms);
        }
      );
    }

Notes

  • Promises are natively supported since ES2015. If you are using ES5 you may want to use one of the many polyfill libraries for Promises.