eguneys
eguneys

Reputation: 6396

How to perform an async task against es6 generators in loop

I understand how to use generators to make async code look nice. I have a simple generator *all, that takes a page, will return a single value.

Then I have another generator *allDo, that will use *all for pages 1 to 30 and for each result, do some async task.

Then I have another generator *allBatchDo, that will batch 3 pages, and do some async task.

function mockPromise(value) {
  return Promise(function(resolve, reject) {
    resolve(value);
  });
}

function *all(page) {
  var ls = yield mockPromise("page " + page);
  // do all kinds of promises
  return yield ls;
};

function *allDo(task) {
  var page = 1;
  while (true) {
    var res = yield * all(page);

    res = yield task(res);

    if (page == 30) {
      break;
    }
    page++;
  }
}

function *allBatchDo(task) {
  var page = 1;
  var arr = [];
  while (true) {
    var res = yield * all(author, page);

    arr.push(res);
    if (arr.length >= 3) {
      yield task(arr);
      arr = [];
    }

    if (page == 30) {
      break;
    }

    page++;
  }
}

function logTask(res) {
  return mockPromise(res).then(function(v) {
    console.log(v);
  });
}

Example use of these generators would be:

// return a single page promise
async(all(1)).then(function(value) { console.log(value); });

// do `logTask` for all pages 1 thru 30
async(allDo(logTask));

// do `logTask` for all pages with batches of 10
async(allBatchDo(logTask));

The question is, is this a legitimate use of es6 async features, or is there an abstract built-in solution for my use case?

Upvotes: 8

Views: 1946

Answers (3)

Daljeet Singh
Daljeet Singh

Reputation: 714

Below are some links that can help you for asynquence's runner

http://davidwalsh.name/concurrent-generators And http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html

Upvotes: 0

kruczy
kruczy

Reputation: 791

I would say this code might be quite slow, since you are using yield* all the task will run sequentially potentially taking much more time than necessary (assuming mockPromise does some io) you might be better of yielding Promise.all or just using promises

also your usage of while(true) is very weird..

Upvotes: 0

sribin
sribin

Reputation: 1736

If you want use generators to make async then you code is valid. ES6 contains only promises to async operations. ES7 will have async/await. You can also use a good library: https://github.com/kriskowal/q or use only native promises Promise.All without generators.

Upvotes: 4

Related Questions