Horje
JavaScript AsyncGenerator.prototype.next() method

JavaScript AsyncGenerator.prototype.next() method is used with the asynchronous generators to retrieve the next value in the sequence produced by the generator. It returns a Promise that resolves to the object with two properties: value and done.

Syntax:

AsyncGenerator.prototype.next(value);

Parameters: This method accepts only one parameter as shown in the above syntax and explained below:

  • value: The value to be passed to the generator as the result of the last yield expression. It will be the result of the current yield expression inside the generator function.

Return Value: The return value is a Promise that resolves to an object with the two properties:

  • value: The resolved value of the generator which is the value yielded by the generator function.
  • done: A boolean value, indicates whether the generator has completed or not.

The below examples will explain the practical implementation of the AsyncGenerator.prototype.next() method.

Example 1: In the below article, we will create a generator function and then use the next() method on it by creating an instance of it.

Javascript

async function* asyncGenerator() {
    yield 3;
    yield 5;
    yield 3;
}
const generator = asyncGenerator();
generator.next().then(result => {
    console.log(result.value);
    console.log(result.done);
});
generator.next().then(result => {
    console.log(result.value);
    console.log(result.done);
});
generator.next().then(result => {
    console.log(result.value);
    console.log(result.done);
});

Output

3
false
5
false
3
false

Example 2: This example will illustrate the use of the asyncGenerator function and the next() method with the string values.

Javascript

async function* asyncGenerator() {
    yield 'HI';
    yield 'Async';
    yield 'Generator';
}
const generator = asyncGenerator();
generator.next().then(result => {
    console.log(result.value);
    console.log(result.done);
});
generator.next().then(result => {
    console.log(result.value);
    console.log(result.done);
});
generator.next().then(result => {
    console.log(result.value);
    console.log(result.done);
});

Output

HI
false
Async
false
Generator
false

Supported Browsers: The browsers supported by Generator.prototype.next() method are listed below:

  • Google Chrome
  • Firefox
  • Opera
  • Safari
  • Edge



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
How to create and send GET requests in Postman? How to create and send GET requests in Postman?
Javascript AsyncGenerator.prototype.throw() Method Javascript AsyncGenerator.prototype.throw() Method
How to Copy and Paste Text and Images in Google Docs How to Copy and Paste Text and Images in Google Docs
What is Backlog refinement or Grooming in Agile Scrum? What is Backlog refinement or Grooming in Agile Scrum?
What is Appium? What is Appium?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12