Atomics.waitAsync()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The Atomics.waitAsync()
static method waits asynchronously on a shared memory location and returns an object representing the result of the operation.
Unlike Atomics.wait()
, waitAsync
is non-blocking and usable on the main thread.
Note: This operation only works with an Int32Array
or BigInt64Array
that views a SharedArrayBuffer
.
Syntax
Atomics.waitAsync(typedArray, index, value)
Atomics.waitAsync(typedArray, index, value, timeout)
Parameters
typedArray
-
An
Int32Array
orBigInt64Array
that views aSharedArrayBuffer
. index
-
The position in the
typedArray
to wait on. value
-
The expected value to test.
timeout
Optional-
Time to wait in milliseconds.
NaN
(and values that get converted toNaN
, such asundefined
) becomesInfinity
. Negative values become0
.
Return value
An Object
with the following properties:
async
-
A boolean indicating whether the
value
property is aPromise
or not. value
-
If
async
isfalse
, it will be a string which is either"not-equal"
or"timed-out"
(only when thetimeout
parameter is0
). Ifasync
istrue
, it will be aPromise
which is fulfilled with a string value, either"ok"
or"timed-out"
. The promise is never rejected.
Exceptions
TypeError
-
Thrown if
typedArray
is not anInt32Array
orBigInt64Array
that views aSharedArrayBuffer
. RangeError
-
Thrown if
index
is out of bounds in thetypedArray
.
Examples
Using waitAsync()
Given a shared Int32Array
.
const sab = new SharedArrayBuffer(1024);
const int32 = new Int32Array(sab);
A reading thread is sleeping and waiting on location 0 which is expected to be 0.
The result.value
will be a promise.
const result = Atomics.waitAsync(int32, 0, 0, 1000);
// { async: true, value: Promise {<pending>} }
In the reading thread or in another thread, the memory location 0 is called and the promise can be resolved with "ok"
.
Atomics.notify(int32, 0);
// { async: true, value: Promise {<fulfilled>: 'ok'} }
If it isn't resolving to "ok"
, the value in the shared memory location wasn't the expected (the value
would be "not-equal"
instead of a promise) or the timeout was reached (the promise will resolve to "time-out"
).
Specifications
Specification |
---|
ECMAScript Language Specification # sec-atomics.waitasync |
Browser compatibility
BCD tables only load in the browser