In this final section, we'll look at the Promise.resolve()
and Promise.reject()
methods. We've already seen how Promise.resolve()
can resolve thenable objects earlier in the chapter. It can also directly resolve values or other promises. These methods come in handy when we implement a function that has the potential to be both synchronous and asynchronous. This isn't a situation we want to find ourselves in using a function with ambiguous concurrency semantics.
For example, here's a function that's both, synchronous and asynchronous, leading to confusion, and almost certainly to bugs later on:
// Example function that returns "value" from // a cache, or "fetchs" it asynchronously. function getData(value) { // If it exists in the cache, we return // this value. var index = getData.cache.indexOf(value); if (index > -1) { return getData.cache[index]; } // Otherwise, we have to go "fetch" it. This // "resolve()" call would typically...