mirror of
https://github.com/alrayyes/wiki.git
synced 2024-12-01 15:26:23 +00:00
1.2 KiB
1.2 KiB
id | title |
---|---|
fc8cc294-ab54-44cb-8a3a-f18036ffe175 | JavaScript Async Iterator |
Syntax
async function* createAsyncIterable(syncIterable) {
for (const elem of syncIterable) {
yield elem;
}
}
const asyncIterable = createAsyncIterable(["a", "b"]);
const asyncIterator = asyncIterable[Symbol.asyncIterator]();
asyncIterator
.next()
.then((iterResult1) => {
console.log(iterResult1);
return asyncIterator.next();
// { value: 'a', done: false }
})
.then((iterResult2) => {
console.log(iterResult2);
return asyncIterator.next();
// { value: 'b', done: false }
})
.then((iterResult3) => {
console.log(iterResult3);
// { value: undefined, done: true }
});
TypeScript interfaces
The interfaces, in TypeScript notation:
interface AsyncIterable {
[Symbol.asyncIterator](): AsyncIterator;
}
interface AsyncIterator {
next(): Promise<IteratorResult>;
}
interface IteratorResult {
value: any;
done: boolean;
}