Computer >> Computer tutorials >  >> Programming >> Javascript

What is the importance of 'for await...of' statement in JavaScript?


for await...of

The 'for await...of' statement creates a loop iterating over async objects and sync objects such as arrays, array-like objects, maps sets, etc.

syntax

for await (variable of iterable) {
   statement
}

Example

In the following example "for await...of" statement is used to loop over a normal array in an async format and integers were displayed from 1 to 5 as shown in the output.

<html>
<body>
<script>
   var txt = "";
   const array = [1,2,3,4,5];
   async function test() {
      for await (const p of array) {
         var txt = p + "</br>";
         document.write(txt);
      }
   }
   test();
</script>
</body>
</html>

Output

1
2
3
4
5


To call an async function in a loop, a new Symbol "Symbol.asyncIterator" and "for-await...of" construct are used. Most importantly "for-await...of" has played an important role to loop over async iterable object.   

Example

In the following example using "for await...of", which iterates over an async iterable, integers from 1 to 5 were displayed.

<html>
<body>
<script>
   var txt = "";
   var async = {
      [Symbol.asyncIterator]() {
         return {
            i: 1,
            next() {
               if (this.i < 6) {
                  return Promise.resolve({ value: this.i++, done : false});
               }
            }
         };
      }
   };
   async function test() {
      for await (let p of async) {
         txt = p + "</br>"
         document.write(txt);
      }
   }
   test();
</script>
</body>
</html>

Output

1
2
3
4
5