Promise.all Progress From Per-Task Hooks

Promise.all only reports final settlement; attaching a then hook to each task yields an incremental progress count without changing result order.

JavascriptData Fetching

Code

javascriptsnippet
17 lines
// Promise.all 只报"最终成败";要进度就得给每个任务挂自己的 .then 计数
const files = ['alpha', 'beta', 'gamma', 'delta'];
let done = 0;
const total = files.length;

const tasks = files.map((name) =>
  Promise.resolve(`payload of ${name}`).then((data) => {
    done += 1;
    console.log(`progress ${done}/${total} - ${name}`);
    return data;
  }),
);

const results = await Promise.all(tasks);
// results 顺序仍与输入一致:进度只反映完成数,不改变结果次序
console.log('results:', results.map((r) => r.split(' of ')[1]).join(','));
console.log('done:', done, 'of', total);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

progress 1/4 - alpha
progress 2/4 - beta
progress 3/4 - gamma
progress 4/4 - delta
results: alpha,beta,gamma,delta
done: 4 of 4

Promise.all Progress From Per-Task Hooks: how the code works

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Top-level bindings files, done, total, tasks hold the demo state — nothing sits inside a function scope.

What to watch for

  • The whole dependency story is the language version itself.

Putting it to use

In the run output, the progress $, results:, done: prefixes each identify the step that emitted the line.

Core lines

Promise.resolve(`payload of ${name}`).then((data) => {
  done += 1;
  console.log(`progress ${done}/${total} - ${name}`);
  return data;
}),
const results = await Promise.all(tasks);

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `files`, `done`, `total`.