Sub topic 10
Non-Blocking Waits with Atomics.waitAsync
This chapter assumes you know how Atomics.wait and Atomics.notify work from the previous chapter. It also assumes you are comfortable with Promises and the event loop.
Why a Non-Blocking Wait Exists
Atomics.wait puts the whole thread to sleep. That works in a worker. On the browser main thread, though, it throws a TypeError, because a sleeping main thread would freeze rendering and input. Atomics.waitAsync waits on the same memory slot but hands you a Promise. The thread keeps running its event loop while it waits.
| Feature | `Atomics.wait` | `Atomics.waitAsync` |
|---|---|---|
| Blocks the thread | Yes | No |
| Browser main thread | Throws `TypeError` | Allowed |
| Return type | String | Object `{ async, value }` |
| Woken by `Atomics.notify` | Yes | Yes |
The Return Shape
Atomics.waitAsync(i32, index, expected, timeout) first checks i32[index] against expected, atomically. The result depends on that check:
- If the value already differs, it returns
{ async: false, value: 'not-equal' }. - If
timeoutis0and the values match, it returns{ async: false, value: 'timed-out' }. - Otherwise it returns
{ async: true, value: promise }. The promise resolves to'ok'when notified or'timed-out'when the timeout expires.
await accepts both plain values and Promises, so you can hide the two cases behind one helper:
async function waitForChange(i32, index, expected, timeout = Infinity) {
const result = Atomics.waitAsync(i32, index, expected, timeout);
return result.value; // a string, or a Promise of a string
}A Runnable Example
In this Node.js script the main thread waits without blocking. A worker changes the flag after 200 ms. The interval timer keeps printing during the wait, which shows the event loop is still running.
const { Worker, isMainThread, workerData } = require('node:worker_threads');
if (isMainThread) {
const flag = new Int32Array(new SharedArrayBuffer(4));
const timer = setInterval(() => console.log('main thread still responsive'), 50);
const result = Atomics.waitAsync(flag, 0, 0, 5000);
new Worker(__filename, { workerData: flag.buffer });
Promise.resolve(result.value).then((outcome) => {
clearInterval(timer);
console.log('outcome:', outcome, 'flag:', Atomics.load(flag, 0)); // outcome: ok flag: 1
});
} else {
const flag = new Int32Array(workerData);
setTimeout(() => {
Atomics.store(flag, 0, 1);
Atomics.notify(flag, 0);
}, 200);
}Common Errors
- Treating
valueas always a Promise. Calling.thenon'not-equal'throws. Checkasyncfirst, or wrap the value withawaitorPromise.resolve. - Assuming
'ok'means the value changed.'ok'only means some thread callednotify. Read the slot again, and loop if the condition you need is still false. - Wrong array type. Only an
Int32Arrayor aBigInt64Arrayover aSharedArrayBufferworks. Any other array throws aTypeError. - Forgetting the notify count. Async waiters count toward
Atomics.notify'scountargument just like blocking waiters do. If you pass1, only one waiter wakes. - Missing support. Older engines lack
waitAsync. Feature-detect it withtypeof Atomics.waitAsync === 'function'.
Exercise
The flag is already 1 when you call Atomics.waitAsync(flag, 0, 0, 1000). What does the call return, and what happens if your code calls result.value.then(...)?
Show answer
It returns { async: false, value: 'not-equal' } at once, because the slot does not hold the expected value 0. Here result.value is the string 'not-equal', not a Promise, so calling .then on it throws a TypeError.
Exercise
Write an async function waitUntilNonZero(i32, index) that resolves once i32[index] is non-zero, even if a notify arrives without a change.
Show answer
async function waitUntilNonZero(i32, index) { while (Atomics.load(i32, index) === 0) { await Atomics.waitAsync(i32, index, 0).value; } return Atomics.load(i32, index); }