JavaScript中的循环是同步还是异步? (对,同时,等)javascript中的同步和异步循环
假如我有:
for(let i=0; i<10; i++){
// A (nested stuff...)
}
// B ...
使用for
的B
执行将开始之前A
有时......(所以异步)
是否有使用方法语句以同步的方式?
JavaScript中的循环是同步还是异步? (对,同时,等)javascript中的同步和异步循环
假如我有:
for(let i=0; i<10; i++){
// A (nested stuff...)
}
// B ...
使用for
的B
执行将开始之前A
有时......(所以异步)
是否有使用方法语句以同步的方式?
当所有的异步操作开始时,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"]
);
让我知道如果我不够清晰。
如果在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()
_“使用'for'执行'B'会在'A'有时候''之前开始_您可以创建一个堆栈片段来演示吗? – guest271314
@ guest271314它可以是任何东西,更多的嵌套语句,ajax,逻辑等等 – neoDev
'for'循环是同步的。 'for'循环完成之前不应执行'B'。你能证明'B'“somtimes”在'for'循环完成之前开始执行吗? 'for'循环中是否有异步操作,在'B'开始执行之后,在将来的某个时间可能不会调用?请参阅http://stackoverflow.com/help/mcve。 – guest271314