Create promise

A promise.

new Promise()

An immediately-resoving promise:

Promise.resolve('My value')

An immediately-failing promise:

Promise.reject(new Error('My error message'))

A promise that resolves after a delay, to match waiting on a network request. We pass a function

new Promise(resolve => {
    setTimeout(() => {
      resolve(`resolved at ${(new Date()).toTimeString()}`);
    }, 2000);
  });

In a function:

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(`resolved at ${ (new Date()).toTimeString() }`);
    }, 2000);
  });
}

Resolve and reject

new Promise(resolve => {
    resolve("Success value")
});
new Promise((resolve, reject) => {    
    reject("Failure value")
    // OR
    reject(throw new Error("Failure value"))
    
    resolve("Success value")
});

Promise.all

Wait for a batch of promises to resolve. The calls start at the same time and finish in any order (so this is great for requests to APIs that are independent). This will only resolve after the last one has resolved.

Promise.all(ARRAY_OF_PROMISES)

e.g.

(async function () {
  console.log((new Date()).toTimeString())

  const timers = [resolveAfter2Seconds(), resolveAfter2Seconds(), resolveAfter2Seconds()]
  const values = await Promise.all(timers)
  console.log(`All done at ${(new Date()).toTimeString()}`)
  console.log({ values })
})()

Note this takes 2 seconds but we donโ€™t see the logs from inside each call for some reason.

17:41:30 GMT+0200 (South Africa Standard Time)
All done at 17:41:32 GMT+0200 (South Africa Standard Time)
{
  values: [
    'resolved at 17:41:32 GMT+0200 (South Africa Standard Time)',
    'resolved at 17:41:32 GMT+0200 (South Africa Standard Time)',
    'resolved at 17:41:32 GMT+0200 (South Africa Standard Time)'
  ]
}