egu*_*eys 8 javascript asynchronous ecmascript-6 co
我理解如何使用生成器使异步代码看起来不错.我有一个简单的生成器*all,它需要一个page,将返回一个值.
然后我有另一个生成器*allDo,将*all用于第1到30页,并为每个结果,做一些异步task.
然后我有另一台发电机*allBatchDo,它将批量3页,并做一些异步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);
});
}
Run Code Online (Sandbox Code Playgroud)
这些发电机的使用示例如下:
// 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));
Run Code Online (Sandbox Code Playgroud)
问题是,这是es6异步功能的合法使用,还是我的用例有一个抽象的内置解决方案?
如果您想使用生成器进行异步,那么您的代码是有效的。ES6 仅包含异步操作的承诺。ES7 将有 async/await。您还可以使用一个好的库:https://github.com/kriskowal/q或仅使用本机承诺 Promise.All 而不使用生成器。