Atomics.waitAsync()

Atomics.waitAsync() 静态方法在共享内存位置异步等待并返回 Promise

¥The Atomics.waitAsync() static method waits asynchronously on a shared memory location and returns a Promise.

Atomics.wait() 不同,waitAsync 是非阻塞的并且可在主线程上使用。

¥Unlike Atomics.wait(), waitAsync is non-blocking and usable on the main thread.

注意:此操作仅适用于查看 SharedArrayBufferInt32ArrayBigInt64Array

¥Note: This operation only works with an Int32Array or BigInt64Array that views a SharedArrayBuffer.

语法

¥Syntax

js
Atomics.waitAsync(typedArray, index, value)
Atomics.waitAsync(typedArray, index, value, timeout)

参数

¥Parameters

typedArray

查看 SharedArrayBufferInt32ArrayBigInt64Array

index

typedArray 的位置等待。

value

要测试的期望值。

timeout Optional

等待时间以毫秒为单位。NaN(以及转换为 NaN 的值,例如 undefined)变为 Infinity。负值变为 0

返回值

¥Return value

Object 具有以下属性:

¥An Object with the following properties:

async

一个布尔值,指示 value 属性是否为 Promise

value

如果 asyncfalse,则为 "not-equal""timed-out" 中的一个字符串(仅当 timeout 参数为 0 时)。如果 asynctrue,那么它将是一个由字符串值("ok""timed-out")填充的 Promise。承诺永远不会被拒绝。

例外情况

¥Exceptions

TypeError

如果 typedArray 不是查看 SharedArrayBufferInt32ArrayBigInt64Array,则抛出该异常。

RangeError

如果 indextypedArray 中出界,则抛出该球。

示例

¥Examples

使用 waitAsync()

¥Using waitAsync()

给定一个共享的 Int32Array

¥Given a shared Int32Array.

js
const sab = new SharedArrayBuffer(1024);
const int32 = new Int32Array(sab);

读取线程正在睡眠并等待位置 0,该位置预计为 0。result.value 将是一个承诺。

¥A reading thread is sleeping and waiting on location 0 which is expected to be 0. The result.value will be a promise.

js
const result = Atomics.waitAsync(int32, 0, 0, 1000);
// { async: true, value: Promise {<pending>} }

在读取线程或另一个线程中,调用内存位置 0,并且可以使用 "ok" 解析 Promise。

¥In the reading thread or in another thread, the memory location 0 is called and the promise can be resolved with "ok".

js
Atomics.notify(int32, 0);
// { async: true, value: Promise {<fulfilled>: 'ok'} }

如果它没有解析为 "ok",则共享内存位置中的值不是预期的(value 将是 "not-equal" 而不是承诺)或已达到超时(承诺将解析为 "time-out")。

¥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").

规范

Specification
ECMAScript Language Specification
# sec-atomics.waitasync

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看