如何在vo.js的for循环中产生多个promise?

时间:2017-04-19 06:02:15

标签: javascript node.js for-loop promise flow-control

基于这个例子 - vo/examples/9-pipeline-composition.js,我将如何return yield对此for循环的每次迭代作出承诺?

此时循环运行一次并产生一个承诺。

 function * get (urls) {
    for (var i = urls.length - 1; i >= 0; i--) {
        console.log(urls[i])
        return yield http.get(urls[i]) 
    }
}

function status (res, params) {
    return res.status
}

let scrape = vo(get(['http://standupjack.com', 'https://google.com']), status)

vo([ scrape ])
.then(out => console.log('out', out))
.catch(e => console.error(e))

1 个答案:

答案 0 :(得分:1)

当你在for循环中返回时,循环中断并返回结果,循环不会向前移动。你可以在for循环中调用一个函数来处理结果而不返回它。

function * get (urls) {
  for (var i = urls.length - 1; i >= 0; i--) {
    console.log(urls[i])
    let result = yield http.get(urls[i])
    yield handleResult(result)
  }
}

Orelse你可以将每个结果推送到一个数组中并在结尾处将所有结果一起返回

function * get (urls) {
  let resArr = []
  for (var i = urls.length - 1; i >= 0; i--) {
    console.log(urls[i])
    let result = yield http.get(urls[i])
    resArr.push(result)
  }
  return resArr
}