// An async task. Pretend it's doing something more useful
// in practice.
function delayedValue(time, value) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(value), time);
});
}
async function* createAsyncGenerator() {
yield delayedValue(500, 1);
yield delayedValue(500, 2);
yield delayedValue(500, 3);
}
const asyncGen = createAsyncGenerator();
asyncGen.next().then((res) => console.log(res)); // { value: 1, done: false }
asyncGen.return("foo").then((res) => console.log(res)); // { value: "foo", done: true }
asyncGen.next().then((res) => console.log(res)); // { value: undefined, done: true }AsyncGenerator.prototype.return() / notebook
AsyncGenerator.prototype.return()
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
async function* createAsyncGenerator() {
yield Promise.resolve(1);
yield await Promise.resolve(2);
yield 3;
}
const asyncGen = createAsyncGenerator();
asyncGen.next().then((res) => console.log(res)); // { value: 1, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: 2, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: 3, done: false }
// value is returned undefined, as no value is passed and generator is 'done'
asyncGen.return().then((res) => console.log(res)); // { value: undefined, done: true }
// we can still return a value once the generator is complete
asyncGen.return(1).then((res) => console.log(res)); // { value: 1, done: true }