How can I use Async Generators in JavaScript?

前端 未结 2 1204
无人及你
无人及你 2021-01-19 11:20

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({
    result         


        
相关标签:
2条回答
  • 2021-01-19 11:42

    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.

    let api = (value) => {
      return new Promise((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 {
        yield fn(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));

    0 讨论(0)
  • 2021-01-19 11:49

    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 = async function * () {
      for (let i = 0; i < 10; i++) {
        const xs = await g(i);
        for (const x of xs) {
          yield x;
        }
      }
    };
    
    const main = async () => {
      for await (const x of f()) {
        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" ]
     }
    
    0 讨论(0)
提交回复
热议问题