Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
12.12. Run an array of promise-returning functions in sequence
Easy
Topics
This question is in
12. Callbacks, promises and asyncSome work is a pipeline: each step takes the previous step's result and returns a promise of the next one. Upload a photo, then make a thumbnail from the upload, then save the thumbnail's address on the user's profile. The list of steps may be built at run time, so it cannot be written as a fixed chain; it has to be run from an array, one step at a time, with each result passed along.
Write runSequence(fns, initial) in run-sequence.js.
Signature
function runSequence(fns, initial) // returns a Promisefns: an array of functions. Each takes one value and returns a promise or a plain value.initial: the first function's input. If it is a promise, its value is used.- The promise fulfills with the last function's result.
Requirements
runSequencereturns a promise. No function is called during the call itself: the first one starts in a microtask.- The first function receives
initial(once it has settled, if it is a promise); each next function receives what the previous one fulfilled with. - Each function starts only after the previous one has fulfilled, and right away when it has.
- The promise fulfills with the last function's result, after it. With no functions, it fulfills with
initial. - At the first rejection, or throw, the promise rejects with it, and no later function is called.
- Plain return values are passed along like fulfilled promises.
- The array of functions is not changed, and a thousand functions work.
Examples
const later = (ms, fn) => (value) => new Promise((resolve) => setTimeout(() => resolve(fn(value)), ms));
await runSequence([
later(300, (file) => `uploaded/${file}`),
later(100, (path) => `${path}.thumb`),
later(50, (thumb) => ({ avatar: thumb })),
], "cat.png");
// after 450 ms: { avatar: "uploaded/cat.png.thumb" }await runSequence([(n) => n + 1, (n) => n * 2], 3); // 8
await runSequence([], "unchanged"); // "unchanged"await runSequence([(n) => n, () => { throw new Error("thumbnail failed"); }, (n) => n], 1);
// rejects with "thumbnail failed"; the third function never runsEnvironment
- Plain JavaScript in a browser page; the tests call the global
runSequencefromrun-sequence.js. - The tests' functions answer on a virtual clock (
setTimeout), so no test waits for real time. async/awaitis allowed, but try writing it as one promise chain.
Hints
- A chain for two functions is
Promise.resolve(initial).then(f1).then(f2). Which array method builds that from a list? - What happens to the next
.thenhandler when a handler throws?
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
Back to the question
Loading the editor…