DEV Community


Posted on

Promises in JS

A promise is an object that may produce a single value some time in the future - either a result or a reason it's not resolved (rejected).

The advantage of promises is that they run asynchronously in the background and it allows your code to run continue execution while the promise waits for a response (a common use case is to interact with API's as there may be some lag time).

You might already be familiar with promises: fetch() is a promise!

Basic syntax for creating a new promise:

const promise = new Promise((resolve, reject) => {
  if (true) {
    resolve("it worked!");
  } else {
    reject("error! it did not work");

  .then(result => result + " some action taken on returned result")
    secondResult => secondResult + " some action taken on the second result"
  .catch(error => console.log("an error occurred", error));

Another useful tool is the Promise.all() call, which will take an array of multiple promises and once they have resolved, return all of them at the same time. For example:

const oneSec = new Promise((resolve, reject) => {
  setTimeout(resolve, 1000, "One second resolved");

const twoSec = new Promise((resolve, reject) => {
  setTimeout(resolve, 2000, "One second resolved");

const fiveSec = new Promise((resolve, reject) => {
  setTimeout(resolve, 5000, "One second resolved");

Promise.all([oneSec, twoSec, fiveSec]).then(values => {

If you copy and paste all of the above code snippet into your terminal and count off the seconds, you'll notice that after five seconds, all of the values are returned, even though the first two would have taken less time to resolve if they were called individually.
So the caveat with Promise.all() is that it can return multiple values, but will only return the values after the slowest call has resolved.
You can also see this in action by running the promises without the Promise.all() call. If you then run the Promise.all() it will be instant because they have already run and the result is now stored in the variables.

Top comments (0)