Open In App

JavaScript AsyncGenerator.prototype.next() method

Last Updated : 07 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads