javascript中的同步和异步循环 [英] synchronous and asynchronous loops in javascript

查看:133
本文介绍了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 ...

使用执行 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.

这篇关于javascript中的同步和异步循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆