2017-04-19 92 views
1

基於這個例子 - vo/examples/9-pipeline-composition.js,我如何return yield這個for循環的每個迭代的承諾?如何在vo.js 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

當您在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) 
    } 
} 

否則容易u能推每個結果的在陣列中,並在端

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 
} 
返回所有的然後一起