Skip to content
Related Articles

Related Articles

Improve Article

JavaScript Symbol.asyncIterator Property

  • Last Updated : 13 Apr, 2021

The Symbol.asyncIterator property is used to set an object as an async iterable. Iterable properties of this object can be iterated over using a for await…of loop.

An async iterable object is any object that returns a function which produces an AsyncIterator for its Symbol.asyncIterator property.

The Symbol.asyncIterator symbol is a built-in symbol that is used to access an object’s @@asyncIterator method. 

Note: For an object to be an async iterable, it must have a Symbol.asyncIterator key.

Property attributes of Symbol.asyncIterator
Writableno
Enumerableno
Configurableno

Example codes for the above property are as follows:



Example 1:

Javascript




<script>
    // JavaScript program to demonstrate
    // the Symbol.asyncIterator Property
      
    // Defining an async iterable 
    const GFG = {
  
        // Setting the [Symbol.asyncIterator] 
        // property on the object
        async*[Symbol.asyncIterator]() {
  
            // Using yield keyword to pause
            // and resume generator function
            let i = 0;
            while (i < 10) {
                if (i % 3 == 0) {
                    yield i;
                }
                i++;
            }
        }
  
    };
  
    (async () => {
  
        // Iterate over the async iterable
        // object i.e. myAsyncIterable
        // using for await... loop
        for await (const x of GFG) {
            document.write(x + "<br>");
        }
    })();
  
</script>

Output: 

0
3
6
9

Example 2:

Javascript




<script>
    // JavaScript program to demonstrate
    // the Symbol.asyncIterator Property
  
    // Defining an async iterable 
    const myAsyncIterable = {
  
        // Setting the [Symbol.asyncIterator] 
        // property on the object
        async*[Symbol.asyncIterator]() {
  
            let i = 0;
            while (i < 5) {
  
                // Using yield keyword to 
                // yield values of i
                yield i++;
            }
        }
    };
  
    (async () => {
  
        // Iterate over the async iterable
        // object i.e. myAsyncIterable
        // using for await... loop
        for await (const num of myAsyncIterable) {
            document.write(num + "<br>");
        }
    })();
  
</script>

Output

0
1
2
3
4

Browser Support: The browsers supported by JavaScript Symbol.asyncIterator Property are listed below:

  • Google Chrome
  • Firefox
  • Edge
  • Opera
  • Safari



My Personal Notes arrow_drop_up
Recommended Articles
Page :