2017-02-11 99 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()