实现说明
逻辑集中在函数 sleep、worker、bump、main里。
循环只出现在 for (const step of steps),它的每次迭代处理一个元素。await 点把异步工作排成序列,拒绝落在取结果的那一行。
使用要点
- 直接运行文件,输出会带上标签,比如
counter after 3 bumps:——输出的每一行都能指回产生它的那次调用。 - 执行文件,
main会按顺序走完worker、bump。
常见问题
运行「await 挂起点让并发任务交错」会打印什么?
运行文件本身,counter after 3 bumps: 这些前缀各对应一段演示逻辑。
入口签名:const sleep = (ms)
核心语句
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await Promise.all([worker('A', [1, 2]), worker('B', [1, 2])]);
await Promise.all([bump(), bump(), bump()]);
代码示例
// every await yields control: concurrent tasks interleave as each one suspends
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const log = [];
async function worker(name, steps) {
for (const step of steps) {
log.push(name + ' start ' + step);
await sleep(10); // suspension point: the other task advances here
log.push(name + ' done ' + step);
}
}
let counter = 0;
async function bump() {
const current = counter; // read
await sleep(5); // suspension: the other two bumps complete their reads in the meantime
counter = current + 1; // writes back a stale value -> lost update
}
async function main() {
await Promise.all([worker('A', [1, 2]), worker('B', [1, 2])]);
console.log(log.join(' -> '));
await Promise.all([bump(), bump(), bump()]);
console.log('counter after 3 bumps:', counter, '(lost updates)');
}
main();