CO模块如何循环?
发布于 8 年前 作者 firhome 3846 次浏览 来自 问答

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 回复

建议用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好了

@andyhu

Promise.coroutine 应该等于 co.wrap …

for(let i of index){
  const detail = yield getDetail(i);
}

可以 for 的 …

回到顶部