CNode

CO模块如何循环?

问答
Ffirhome发布于10 年前最后回复10 年前4 回复4700 浏览0 收藏

co(function *(){ var index = yield getIndex(); // 我这个index是去抓取一堆数组 如[1,2,3,4]; var detail = yield getDetail(1); var detail = yield getDetail(2); var detail = yield getDetail(3); var detail = yield getDetail(4); //然后我这个detail根据index返回的参数分别去抓取远程的资源,因为是异步的。所以这里该怎么做呢?直接for一下?

}).then(){}
查看回复

回复 (4)

A
andyhu#1·10 年前

建议用bluebird的coroutine

global.Promise = require('bluebird');
const co = Promise.coroutine;

co内的代码可以当成同步的方式来写,也就是说可以for循环,不过更好的方式是用Promise:

co(function *() {
  const index = yield getIndex();
  const details = yield Promise.all([1,2,3,4], getDetail);
}).then(() => {})

如果不可以并发执行的话,那就用for好了

L
luoyjx#2·10 年前

Promise.map

M
magicdawn#4·10 年前
for(let i of index){
  const detail = yield getDetail(i);
}

可以 for 的 ...

参与回复
登录后即可参与回复。登录