Skip to content Skip to sidebar Skip to footer

How Can I Use Async Generators In Javascript?

I have an api thats going to return a cursor for fetching more data. I've mocked it out like this: function fetch(n) { return Promise.resolve({ results: [n], next: next &

Solution 1:

You can do this using the Babel plugin transform-async-generator-functions.

The usage is like this:

const g = async i => [ 1, 2, 3 ]
  .map(x => x * 10 ** i);

const f = asyncfunction * () {
  for (let i = 0; i < 10; i++) {
    const xs = awaitg(i);
    for (const x of xs) {
      yield x;
    }
  }
};

const main = async () => {
  forawait (const x off()) {
    console.log(x);
  }
};

main().catch(e =>console.error(e));

Here is an example repo showing how to setup your project.

The important part is the .babelrc file:

{"presets":["env"],"plugins":["transform-async-generator-functions"]}

Solution 2:

You can pass call the generator function as parameter to without using spread element, Promise.all() accepts an iterable as parameter which yield returns. Note, Promise.all() does not resolve or reject the passed Promise objects in sequential order, though does return the resulting array in same order as the elements within passed iterable.

letapi = (value) => {
  returnnewPromise((resolve, reject) => {
    setTimeout(() => {
      resolve(value)
    }, Math.floor(Math.random() * 3500))
  })
};

let values = [1, 2, 3];
let results = [];
let gen = function* gen(fn, props) {
  let i = 0; 
  do {
    yieldfn(props[i]).then(res => {console.log(res); return res});
    ++i;
  } while (i < props.length);
}

Promise.all(gen(api, values))
.then(data =>console.log("complete:", data))
.catch(err =>console.log(err));

Post a Comment for "How Can I Use Async Generators In Javascript?"