11.7. Chain calls with optional delays
Topics
This question is in
11. TimersAn onboarding tour shows a tip, waits two seconds, highlights a button, waits again, then opens a panel. A test script types, waits, clicks, waits for a request. Written with nested setTimeout calls, each step sits one level deeper than the last. A chain reads the way the steps happen: tour.do(showTip).wait(2000).do(highlight).wait(1000).do(openPanel), and runs them one after another by itself.
Write chain() in chain.js. It returns an object whose methods queue steps and return the same object, so calls can be chained. The queue starts running on its own once the code that built it has finished.
Signature
function chain() // returns { do, wait, waitFirst, done }do(fn, ...args): queue a call offn(...args). If it returns a promise, the chain waits for it before the next step. Returns the chain.wait(ms): queue a pause ofmsmilliseconds. Returns the chain.waitFirst(ms): put a pause ofmsin front of every step that has not started yet. Returns the chain.done(): returns a promise that resolves, once the queue is empty, with an array of the values everydostep has produced so far (in order), or rejects with the first error.
Requirements
do,waitandwaitFirstreturn the chain itself. The chain is not a thenable: it has nothenmethod.- No step runs while the chain is being built. The chain starts by itself in a microtask once the current code has finished, so a chain with no waits has run before any timer fires.
- Steps run one at a time, in the order they were queued.
fnreceives the extra arguments given todo. wait(ms)delays everything after it byms; waits add up.wait(0)still goes through a 0 ms timer.waitFirst(ms)adds a pause before every step that has not started yet, even if it is called last. A step that is already running (a pause, or an asyncfn) finishes first.- When
fnreturns a promise, the next step starts only after it settles; its resolved value is the step's result. - Steps queued while the chain is running, including from inside a step, run after the steps already queued. Steps queued after the chain has finished start it again.
done()resolves with the results of everydostep so far, as a new array, once nothing is left to run. On a chain that has nothing to do, it resolves with[]straight away.- If
fnthrows or its promise rejects, the chain stops: the remaining steps never run, anddone()rejects with that error, now and on every later call. Steps queued after a failure are ignored. - Each chain is independent of the others.
Examples
chain()
.do(console.log, "a") // 0 ms: a
.wait(100)
.do(console.log, "b") // 100 ms: b
.wait(200)
.do(console.log, "c"); // 300 ms: cchain()
.do(console.log, "a")
.wait(100)
.do(console.log, "b")
.waitFirst(50);
// 50 ms: a, 150 ms: b: the pause went in front of everythingconst results = await chain()
.do(() => 1)
.do(() => new Promise((resolve) => setTimeout(resolve, 100, 2)))
.do((x) => x * 10, 3)
.done();
// results: [1, 2, 30], 100 ms after the startawait chain().do(() => { throw new Error("broken"); }).do(console.log, "never").done();
// rejects with Error("broken"); "never" is not printedEnvironment
- Plain JavaScript in a browser page; the tests call the global
chainfromchain.js. - The tests run on a virtual clock that replaces
setTimeout,clearTimeoutandDate.now; usesetTimeoutfor the waits. Promises andqueueMicrotaskare the real ones. - Canceling a chain, and timeouts for slow steps, are not part of this problem.
Hints
- With every step in one array, which array methods add to the back, add to the front, and take the next step?
- If the steps run inside one
asyncfunction, how can a pause become something that function canawait? - Why must the chain object not have a method called
then?
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