2016-08-05 29 views
0

所以在Node.js的假設我有以下代碼:使爲內循環運行的異步功能系列

for (var i = 0; i < 1000; i++) { 
    someAsynchronousFunction(function(err,res) { 
     // Do a bunch of stuff 
     callback(null,res); 
    }); 
} 

但我想這個同步運行。我知道這不是建議在節點JS,但我只是想了解這種語言。我嘗試實施以下解決方案,但它只是在運行時結束:

for (var i = 0; i < 1000; i++) { 
    var going = true; 
    someAsynchronousFunction(function(err,res) { 
     // Do a bunch of stuff 
     callback(null,res); 
     going = false; 
    }); 
    while (going) { 

    } 
} 

什麼問題和正確的方法是什麼?

回答

1

要做到這一點的最佳方法之一是使用異步庫。

async.timesSeries(1000, function(n, next){ 
    someAsynchronousFunction(next); 
}); 

或者你可以用async.series() function做到這一點。

.times()文檔:http://caolan.github.io/async/docs.html#.timesSeries

+1

真棒,我實際上是在尋找一個異步函數來做到這一點,但我找不到它。 –

+0

您的意思是timesSeries()?此外,並行嚴格異步循環形成性能立場。運行Async.times()或僅執行for循環會更快嗎? –

+0

是的!因爲* .times()*並行運行。對於更快的方式,我不知道。我認爲它必須是相似的,但我們需要一些基準來得出結論。 –

1

另一種方式來做到這一點是用承諾來生成它們感謝到Array#reduce順序執行:

// Function that returns Promise that is fllfiled after a second. 
 
function asyncFunc (x){ 
 
    return new Promise((rs, rj)=>{ 
 
    setTimeout(()=>{ 
 
     console.log('Hello ', x); 
 
     rs(); 
 
    }, 1000) 
 
    }); 
 
} 
 
// Generate an array filed with values : [0, 1, 2, 3, ...] 
 
Array.from({length : 1000}, (el, i)=> i) 
 
// loop througth the array chaining the promises. 
 
.reduce((promise, value) => 
 
    promise.then(asyncFunc.bind(null, value)) 
 
, Promise.resolve(null));