javascriptnode.jsfor-looppromiseflow-control

How to yield multiple promises in for loop with vo.js?


Based on this example - vo/examples/9-pipeline-composition.js, how would I return yield a promise for each iteration of this for loop?

At the moment the loop runs once and yields a single promise.

 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))

Solution

  • When u do the return inside the for loop, the loop breaks and returns the result and the loop wont move forward. You can call a function inside the for loop which handles the result and not return it.

    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 u can push each of the results in an array and return all of then together at the end

    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
    }