13.6. Promise.withResolvers and Promise.try
Topics
This question is in
13. Promise from scratchTwo small helpers fix two everyday annoyances with promises. The first: sometimes the code that settles a promise is not where the promise is made, like a queue that answers a request when a message arrives later. You end up writing let resolve; new Promise((r) => { resolve = r; }) again and again. Promise.withResolvers() gives you the promise and its two settle functions in one object. The second: a function that "returns a promise" can still throw before it gets that far, and then a caller's .catch never sees the error. Promise.try(fn) calls fn and turns everything it does, value, promise or throw, into one promise.
Write both in with-resolvers-try.js, as withResolvers() and promiseTry(fn, ...args).
Signature
function withResolvers() // returns { promise, resolve, reject }
function promiseTry(fn, ...args) // returns a PromisewithResolverstakes no arguments.promiseis a new pendingPromise;resolveandrejectsettle it.promiseTrycallsfnwith the arguments that follow it and returns aPromisefor the outcome.
Requirements
withResolversreturns a plain object with exactly the keyspromise,resolveandreject, in that order.promiseis a realPromise, pending until one of the functions is called.resolve(value)fulfills it andreject(reason)rejects it, at any later time, called as plain functions. Only the first call counts.resolvegiven a promise or a thenable follows it, as thePromiseconstructor'sresolvedoes.- Every call to
withResolversmakes a new promise and new functions. promiseTrycallsfnstraight away, during the call, once, with the extra arguments and withthisundefined.- A value returned by
fnfulfills the promise; a returned promise or thenable is followed. - An error thrown by
fnrejects the promise;promiseTryitself never throws, even whenfnis not a function (it rejects with aTypeError). - Neither calls
Promise.withResolversorPromise.try.
Examples
const { promise, resolve } = withResolvers();
setTimeout(() => resolve("ready"), 100);
promise.then(console.log); // after 100 ms: "ready"promiseTry((a, b) => a + b, 2, 3).then(console.log); // 5promiseTry(() => { throw new Error("bad input"); })
.catch((error) => console.log(error.message)); // "bad input"; nothing escaped the callpromiseTry(() => Promise.reject("not found"))
.catch((reason) => console.log(reason)); // "not found": a returned promise is followedEnvironment
- Plain JavaScript in a browser page; the tests call the globals
withResolversandpromiseTry. - You may use
new Promise. You may not callPromise.withResolversorPromise.try: one test replaces them for a moment to check. - Calling them with a different
this(a subclass) is out of scope.
Hints
- The executor of
new Promiseruns synchronously. What can it do with the two functions it receives so that code outside can use them? - Where must
fnbe called so that its exception becomes a rejection?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it