Monday, September 23, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Atomics waitAsync() Method

JavaScript Atomics waitAsync() Method

Among the Atomic operations the Atomics.waitAsync() operator is used to make an operation wait asynchronously on memory and returns a promise. It is non-blocking as compared to Atomics.wait() and can be used on the main thread. If the promise is not fulfilled then it will lead to a ‘time-out’ status otherwise the status will always be ‘ok’ after the promise has been fulfilled.

Syntax:

Atomics.waitAsync(typedArray, ind, val, timeOut)

Parameters: This operation accepts four parameters.

  • typedArray: It is an Int32Array or BigInt64Array.
  • ind: It is the position of the element to wait on.
  • val: It is the expected value.
  • timeOut: It is the time for which we have to wait. Infinity is the default value.

Return Value: It returns two values where the first value is boolean and tells if the promise is created. If the first value is true then the second value is a Promise which is fulfilled and never rejected 

Example 1: This example shows the use of the waitAsync() method.

Javascript




let example = new SharedArrayBuffer(1024);
let arr = new Int32Array(example);
console.log(Atomics.waitAsync(arr, 0, 0, 1000));


Output:

{ async: true, value: Promise { <pending> } }

Example 2: This example shows the promise fulfilled state.

Javascript




let example = new SharedArrayBuffer(1024);
let arr = new Int32Array(example);
let res = Atomics.waitAsync(arr, 0, 0, 1000)
 
console.log(res);
 
Atomics.notify(arr, 0)
 
setTimeout(() => {
    console.log(res);   
}, 1000);


Output: The notify() method wakes the array and the promise is fulfilled.

{ async: true, value: Promise { <pending> } }
{ async: true, value: Promise { 'ok' } }

Supported Browsers:

  • Chrome
  • Edge
  • Opera
  • Safari

We have a complete list of Javascript Atomic methods, to check those please go through this JavaScript Atomics Reference article.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments