Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

synchronous and asynchronous loops in javascript

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

Supposing I have:

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

// B ...

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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')

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.

Check this out: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...