Write runTasks(tasks) that runs a list of synchronous jobs one per macrotask (yielding with a setTimeout promise between them) and resolves with their results; show that a promise callback queued at the start runs before the first job, and a timer between jobs.
Solution
main.js
const nextTurn = () => new Promise((r) => setTimeout(r, 0));
async function runTasks(tasks) {
const results = [];
for (const [name, job] of tasks) {
await nextTurn(); // one job per event-loop turn
results.push(`${name}=${job()}`);
console.log(`ran ${name}`);
}
return results;
}
Promise.resolve().then(() => console.log("(microtask: runs before any job)"));
setTimeout(() => console.log("(timer task: runs between jobs)"), 0);
runTasks([
["square", () => 12 ** 2],
["reverse", () => [..."loop"].reverse().join("")],
["sum", () => [1, 2, 3, 4].reduce((a, b) => a + b)],
]).then((r) => console.log(r.join(" | ")));
Output Verified by running it on Node.js
(microtask: runs before any job)
(timer task: runs between jobs)
ran square
ran reverse
ran sum
square=144 | reverse=pool | sum=10
The outside timer was queued before runTasks' first nextTurn timer, so it runs first; each job then occupies its own task, leaving room for other work between jobs.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!