2017-02-11 187 views
3

JavaScript中的循環是同步還是異步? (對,同時,等)javascript中的同步和異步循環

假如我有:

for(let i=0; i<10; i++){ 
    // A (nested stuff...) 
} 

// B ... 

使用forB執行將開始之前A有時......(所以異步)

是否有使用方法語句以同步的方式?

+1

_「使用'for'執行'B'會在'A'有時候''之前開始_您可以創建一個堆棧片段來演示嗎? – guest271314

+0

@ guest271314它可以是任何東西,更多的嵌套語句,ajax,邏輯等等 – neoDev

+0

'for'循環是同步的。 'for'循環完成之前不應執行'B'。你能證明'B'「somtimes」在'for'循環完成之前開始執行嗎? 'for'循環中是否有異步操作,在'B'開始執行之後,在將來的某個時間可能不會調用?請參閱http://stackoverflow.com/help/mcve。 – guest271314

回答

6

當所有的異步操作開始時,for循環立即運行完成。

那麼,這裏我們有一些嵌套循環。注意,「BBB」總是在之後發射。

for(let i=0; i<10; i++){ 
    for(let i=0; i<10; i++){ 
    for(let i=0; i<10; i++){ 
     console.log("AA") 
    } 
    } 
} 

console.log('BBB') 

現在,看看這個

for(let i=0; i<10; i++){ 
    setTimeout(function() {console.log("AA")}, 2000) 
} 

console.log('BBB') 

這是因爲一種叫做 「事件循環」。事實上,使用setTimeout我們模擬異步操作。它可能是一個Ajax調用或其他異步過程。

檢查了這一點:http://latentflip.com/loupe

這將真正幫助你瞭解這些各種各樣的異步/同步環的話題。

更新,以顯示如何許諾會在這裏工作(如下評論):

var stringValues = ['yeah', 'noooo', 'rush', 'RP']; 
var P = function(val, idx){ 
    return new Promise(resolve => setTimeout(() => resolve(val), 1000 * idx)); 
}; 


// We now have an array of promises waiting to be resolved. 
// The Promise.all basically will resolve once ALL promises are 
// resolved. Keep in mind, that if at any time something rejects 
// it stops 

// we iterator over our stringValues array mapping over the P function, 
// passing in the value of our array. 
var results = Promise.all(stringValues.map(P)); 

// once all are resolved, the ".then" now fires. It is here we would do 
results.then(data => 
    console.log(data) //["yeah", "noooo", "rush", "RP"] 
); 

讓我知道如果我不夠清晰。

+0

我應該創建一些東西像間隔後解決的承諾? – neoDev

+0

好吧,不是在你原來的問題中,因爲給定一個標準循環 - 它會始終在「BBB」發生之前完成。但是,我的猜測是你有一些異步操作,「可能需要一些時間」,然後「BBB」出現之前,這是正確的嗎? –

+0

是的幾個「可能需要一些時間」 – neoDev

0

如果在for...loop中放置異步循環並且想要停止循環,直到每個操作結束爲止,則必須使用async/await這樣的語法。

async function foo() { 
    var array = [/* some data that will be used async*/] 

    //This loop will wait for each next() to pass the next iteration 
    for (var i = 0; i < array.length; i++) { 
     await new Promise(next=> { 
      someAsyncTask(array[i], function(err, data){ 
       /*.... code here and when you finish...*/ 
       next() 
      }) 
     })   
    } 
} 

foo()