liveBook · Manning

Promise.resolve

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

A Promise factory method that creates a promise already resolved with a given value or assimilates an existing thenable.

Promise.resolve(value) creates a promise that is already resolved with that value. It is useful when a function should return a promise whether its result is already available or still needs to be fetched. section 30.3

const transactions = {};

getTransaction(id) {
  if (transactions[id]) {
    return Promise.resolve(transactions[id]);          1
  } else {
    const loading = load(`/transactions/${id}`);       2
    loading.then(transaction => {
      transactions[id] = transaction;                  3
    });
    return loading;                                    4
  }
}

getTransaction(405).then(transaction => {
  // do something with transaction
}, err => {                                            5
  // handle error
})
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":4,\"ch\":55},{\"line\":4,\"ch\":56}],[{\"line\":6,\"ch\":55},{\"line\":6,\"ch\":56}],[{\"line\":8,\"ch\":55},{\"line\":8,\"ch\":56}],[{\"line\":10,\"ch\":55},{\"line\":10,\"ch\":56}],[{\"line\":14,\"ch\":15},{\"line\":14,\"ch\":16}],[{\"line\":14,\"ch\":17},{\"line\":14,\"ch\":18}],[{\"line\":16,\"ch\":55},{\"line\":16,\"ch\":56}]]"}
!@%STYLE%@!

In the transaction lookup, cached data is wrapped with Promise.resolve; otherwise, the function returns the promise from the network request. Callers can attach success and error handling through .then() either way. section 30.3

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Walks through cached and fetched transaction paths, then shows where callers attach error handling; does not detail Promise internals.
Examples
Uses a transaction lookup that returns cached data or fetches and caches a network result.
What it assumes
Defines promises as eventual values and explains .then() before using Promise.resolve.
What you can do after
Apply Promise.resolve to return cached data as a promise and keep callers on a common promise-based path.
How it connects
Connects Promise.resolve with promises, .then(), memoization, and error handling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.