实现说明
全部逻辑都在函数 tick中。
await 标出每个异步边界——没有 fire-and-forget。
使用要点
- 直接运行文件,输出会带上标签,比如
returned a promise:、wait outcome:、event loop stayed live during the wait:——输出的每一行都能指回产生它的那次调用。
常见问题
包管理器会看到什么?
一份空的依赖清单。示例没有需要抓取的导入。 文件在加载时定义 tick。
主要签名是 function tick()
核心语句
const outcome = await pending.value;
代码示例
// Atomics.wait() blocks the thread until notified; waitAsync is the
// non-blocking variant: it returns a promise so the event loop keeps
// serving timers and I/O while the wait is pending.
const cells = new Int32Array(new SharedArrayBuffer(8));
// Keep timers firing while the wait is pending; stop once the wait settles
let ticking = true;
let ticks = 0;
setTimeout(function tick() {
ticks += 1;
if (ticking) setTimeout(tick, 10);
}, 10);
// Wait up to 100ms for cell 0 to change from 0. Nobody notifies it, so this times out.
const pending = Atomics.waitAsync(cells, 0, 0, 100);
console.log("returned a promise:", pending.async);
// The promise settles with the same result string Atomics.wait would return
const outcome = await pending.value;
ticking = false;
console.log("wait outcome:", outcome);
console.log("event loop stayed live during the wait:", ticks > 0);
// When the observed value is already different, the result is available synchronously
const immediate = Atomics.waitAsync(cells, 0, 99, 1_000);
console.log("already satisfied:", !immediate.async, immediate.value);