Reputation:
This example on MDN explains Symbol.asyncIterator
.
const myAsyncIterable = {
async* [Symbol.asyncIterator]() {
yield "hello";
yield "async";
yield "iteration!";
}
};
(async () => {
for await (const x of myAsyncIterable) {
console.log(x);
// expected output:
// "hello"
// "async"
// "iteration!"
}
})();
My problem is what does async*
mean in the code?
Upvotes: 0
Views: 128
Reputation: 12113
The example given makes use of shorthand for creating methods in object literals or classes. Consider the following object definition:
const iHaveAMethod = {
myMethod() {
return "cool!";
}
};
console.log(iHaveAMethod.myMethod()); // cool!
It also uses bracket syntax to define a method using a symbol.
const iAmASymbol = Symbol("neat");
const iHaveAMethod = {
[iAmASymbol]() {
return "cool!";
}
};
console.log(iHaveAMethod[iAmASymbol]()); // cool!
It creates a method on an object that is a generator (using the *
syntax).
const iHaveAMethod = {
* myMethod() {
yield "cool!";
}
};
console.log(iHaveAMethod.myMethod().next().value); // cool!
Finally, it's an asynchronous method, and so is marked with async
.
const iHaveAMethod = {
async* myMethod() {
yield Promise.resolve("cool!");
}
};
iHaveAMethod.myMethod().next().then(val => console.log(val.value)); // cool!
Combine it with the bracket syntax, and you get async*
:
const iAmASymbol = Symbol("neat");
const iHaveAMethod = {
async* [iAmASymbol]() {
yield Promise.resolve("cool!");
}
};
iHaveAMethod[iAmASymbol]().next().then(val => console.log(val.value)); // cool!
That explains how the async*
got on there. Async iterators and why you'd want an async generator is a whole different ball of wax.
Upvotes: 2