Create a New Promise in JavaScript with the Promise Constructor

InstructorMarius Schulz

Share this video with your friends

Send Tweet

The Promise constructor is used to create a new Promise object. It receives a single function as a parameter (known as the executor function), which in turn receives the resolve and reject functions as parameters:

const promise = new Promise((resolve, reject) => {
  // Perform some operation, then call either resolve() or reject()
});

Within the body of the executor function, you can perform any operation — typically, an asynchronous one. You then either call resolve(value) or reject(reason), depending on the outcome of that operation, to fulfill or reject the promise.

Note that the Promise object is rejected if an error is thrown within the body of the executor function. The return value of the executor function is ignored.

Hosarsiph
~ 6 years ago

I would like to notice the promise chain will break if we throw the error inside the setTimeout. As in the following e.g: https://jsfiddle.net/Hosar/940u8jpx/8/ Instead we should reject the error to keep the chaining. @marius-schulz do you know why this happen ?

Marius Schulzinstructor
~ 6 years ago

@Hosarsiph: The promise is only rejected automatically if the executor function throws synchronously. However, that's not the case here. By the time the code within the setTimeout callback runs, the executor function has been fully executed and exited. Therefore, errors thrown within the setTimeout callback will not automatically reject the promise.

If there's a risk that your code within the setTimeout callback might throw an error, you can wrap a try/catch statement around it and reject the promise yourself:

const sleep = ms => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      try {
        // ...
        throw Error("Some error");
      } catch (error) {
        reject(error);
      }
    }, ms);
  });
};
Hosarsiph
~ 6 years ago

Awesome, thanks for the explanation.