There is this kind of code:
'use strict'; console.log('---'); function getRandom(min, max) { return Math.floor(min + Math.random() * (max - min + 1)); }; var promise = new Promise((resolve) => { setTimeout(() => resolve('загрузился json за секунду'), 1000); }); function getNewArts(setRandomTime, whatIsThisThen) { promise.then(() => { setTimeout(() => { console.log(`грузится ${whatIsThisThen}-я пачка артов за ${setRandomTime} мс`); }, setRandomTime); }); }; getNewArts(getRandom(1400, 2000), 1); getNewArts(getRandom(1400, 2000), 2); getNewArts(getRandom(1400, 2000), 3); This code is designed to emulate the download of json from the server, and then adding images to the DOM.
For an explanation I will sort the code in order.
The strings 'use strict' , 'console,log('---'); and the getRandom() function, I hope, do not need explanations.
Next, I create a new promise that emulates json download from the server here. To emulate asynchrony in the example, I use timers .
Next comes the getNewArts() function, which adds images to the DOM (you need to add them after json is loaded (there is a url for them), so I use promise (so-called promises).
It is necessary to add pictures to the DOM only after the entire new bundle has loaded. To emulate the loading of a new pack of pictures, a timer is used, the load time is generated by the function of random numbers. Next comes, in fact, the call to the getNewArts() function, which loads a new pack.
And here I have a question: after all, it is clear that the load time for pictures can be different, but it is necessary that the packs of pictures be added in accordance with their finished loading in the cache, then how to execute each .then handler sequentially, after executing the pre-installed?
The console displays the text with the time from the very minimum to the maximum, which means that all handlers start executing immediately.
How to fix the code to make it consistent?
You can start console output in snippet. It may be that at the first attempt it will display the correct boot sequence (1, 2, 3), but do not believe it, rerun the test. And here, as it would be desirable:
I draw attention to the time of emulated loading of images, as well as the sequence of execution of .then handlers - they go in order, because the pictures can be loaded at different times, and they need to be output sequentially.
.thenhandlers that I hung up with thegetNewArts()function call are executed sequentially, and not all at the same time and immediately. - VostokSisters