In the code, there are two major problems (out of three) starting javascript developers, I see.Problem one is not understanding asynchronicity.Of course, the cycle is not expecting a return to the asynchronous operation in order to move on. Imagine that you have four hyperactive butlers, and you're throwing them four balls. How are they gonna bring them back? Damn it.And what's inside Promise.then, it's colbec, just written more comfortable.What do we do?Don't:The first solution that comes to mind, and let's wait for the end of the first operation, and then the cycle meter will increase and start the next operation in the next iteration. But you're just turning the asynchronous operation into synchronous and losing all your asynchronic prophysics.We should:To understand that the main problem of this code is not asynchronous, but that you don't understand the circuit. I mean, you're not embarrassed that you're having a consult. json/1_1_1.json So many times? Problem two:ignorance of the areas of visibility in js, they're flooding. The question of the loss of the variable in the cycle is top 1, at interviews with the developer ' s Middle, when the conversation is not answerable. On this resource, this issue is dealt with in different language several times a week. For example https://ru.stackoverflow.com/questions/486204/%D0%9F%D1%80%D0%B8%D0%BD%D1%86%D0%B8%D0%BF-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%8B-%D0%B2%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%BD%D1%8B%D1%85-%D1%84%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D0%B9-%D0%B8%D0%BB%D0%B8-%D0%BD%D0%B5%D0%BF%D0%BE%D0%BD%D1%8F%D1%82%D0%BD%D0%BE%D0%B5-%D0%B7%D0%B0%D0%BC%D1%8B%D0%BA%D0%B0%D0%BD%D0%B8%D0%B5-%D0%B2-javascript (not mentioning a block of scope in es6 true).I mean, the core of your code is like, for(var i = 0; i<4; i++){
setTimeout(function(){console.log(i)}, 1000)
}
setTimeout It's like a simple asynchronous operation. If you don't understand why it'll be four times four, you'll have to meditate until you understand. I will.In brief, this is because the scoop in js for var variables is a function, not a figure box. The cycle of a separate scoop does not form and will all four times refer to the same variable i, the same area of memory.Okay, I get it, I still want it synchronized.In order to control the management of multiple asynchronous requests, there are a number of common libraries, such as http://caolan.github.io/async/ Look at this. async.waterfall