javascript中的同步和异步循环

javascript中的同步和异步循环

问题描述:

JavaScript中的循环是同步还是异步? (for,while等)

Are loops synchronous or asynchronous in JavaScript? (for, while, etc)

假设我有:

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

// B ...

$ c>使用执行 B 将在 A 之前开始有时...(如此异步)

Using for the execution of B will start before A sometimes... (so asynchronous)

是否存在一种以同步方式使用语句的方法吗?

Is there a way to use statements in a synchronous way?

当所有异步操作都启动时,for循环立即运行完成。

The for loop runs immediately to completion while all your asynchronous operations are started.

好吧,这里有一些嵌套循环。注意,BBB总是在之后触发。

Well, here we have some nested loops. Notice, "BBB" always fires after.

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调用或其他异步过程。

This is because of something called the "event loop". And the fact that with that setTimeout we are simulating an async operation. It could be an ajax call or some other async process.

检查出来: http://latentflip.com/loupe

这将真正帮助您了解这些异步/同步循环主题。

This will really help you understand these sorts of async/sync loop topics.

更新以显示承诺如何在这里工作(给出以下评论):

updated to show how promises might work here (given comments below):

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"]
);

如果我不够清楚,请告诉我。

let me know if I am not clear enough.