javascript 中的同步和异步循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42173350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
synchronous and asynchronous loops in javascript
提问by neoDev
Are loops synchronous or asynchronous in JavaScript? (for, while, etc)
JavaScript 中的循环是同步的还是异步的?(为,而等)
Supposing I have:
假设我有:
for(let i=0; i<10; i++){
// A (nested stuff...)
}
// B ...
Using forthe execution of Bwill start before Asometimes... (so asynchronous)
使用for的执行B开始前A,有时......(所以异步)
Is there a way to use statements in a synchronous way?
有没有办法以同步方式使用语句?
采纳答案by james emanon
The for loop runs immediately to completion while all your asynchronous operations are started.
当您启动所有异步操作时,for 循环会立即运行直至完成。
Well, here we have some nested loops. Notice, "BBB" always fires after.
好吧,这里我们有一些嵌套循环。注意,“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')
now, look at this
现在,看看这个
for(let i=0; i<10; i++){
setTimeout(function() {console.log("AA")}, 2000)
}
console.log('BBB')
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.
这是因为所谓的“事件循环”。事实上,使用 setTimeout 我们正在模拟异步操作。它可能是一个 ajax 调用或其他一些异步进程。
Check this out: http://latentflip.com/loupe
看看这个: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):
更新以显示 Promise 在这里的工作方式(下面给出了评论):
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.
如果我不够清楚,请告诉我。
回答by Fernando Carvajal
If you place asynchronous loops inside a for...loopand want to stop the loop until each operation ends, you must use the async/awaitsyntax like this.
如果将异步循环放在 a 中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().then(() => { /*After foo execution*/ })
回答by jales cardoso
let items = YourArray;
let i = 0;
await new Promise(async (resolve, reject) => {
try {
if (items.length == 0) return resolve();
let funSync = async () => {
await yourASyncFunctions(items[i].doAnything);
i++;
if (i == items.length) resolve();
else funSync();
}
funSync();
} catch (e) {
reject(e);
}
});
回答by Squidward Tentacles
Alternative to Get Synchronous For Loop with Make Custom Function Like This:
使用 Make 自定义函数获取同步 For 循环的替代方法,如下所示:
// Declare sync function, sync function is subtitute synchronous for loop in node js !!!
let sync= (length,process,finish,iteration = 0)=>{
if(iteration != length){
let wait= ()=>{
return new Promise(resolve=>{
process(resolve,iteration,length);
});
}
let nextIteration;
if(length > iteration){
nextIteration= iteration+1;
}else{
nextIteration= iteration-1;
}
wait().then((newIteration = nextIteration)=>{
return sync(length,process,finish,newIteration);
});
}else{
finish();
}
}
// Code Above Just Declare The sync() function We Will Use After This !!!
/** sync(param1,param2,param3,param4)
1.param1= the number of iterations you want, type= number;
2.param2= the process that will run when the loop is running, type= function with 3 parameters =>(
a.the first parameter is useful to replace the return or break command in the forloop function,you just call the first parameters with parameters() if you want to end forloop in this iteration.
b.the second parameters will give the number of iteration, type= number.
c.the third parameters give the total of forloop length, type= number. );
3.param3= the function you want to call when the loop is complete, type= function ;
4.param4= the number at the start of the iteration you want, default is zero (0);
**/
// Example :
/** Forloop function like for(i;x;i++), can't make synchronous forloop without custom flow; **/
//I Want To Print "Finished" After 10 Seconds Countdown !!!
sync(0 /** end loop count **/,(end,index)=>{
console.log(index);
setTimeout(()=>{
end(); /** in every iteration I want to reduce one index to make a countdown. **/
},1000)
},()=>{
/** put here the statements you want to run after forloop finish execute ! **/
console.log("Finished");
},10 /** start loop count **/);
回答by Italo José
for(const elment of arrayElements) {
await yourFunc(elment)
await yourOtherFunc('somePatameter')
}

