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:
enter image description here
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.

  • I kind of wrote a lot, but what you want to get is not clear - Grundy
  • @Grundy, so that the .then handlers that I hung up with the getNewArts() function call are executed sequentially, and not all at the same time and immediately. - VostokSisters
  • Add some sample output to the snippet so that you can see it like this now, but you need this way - Grundy
  • @Grundy, painted everything in more detail as I could. There’s nowhere else, I think ... - VostokSisters
  • There is no example of the current output and an example of the expected output in the question. therefore it is not known what exactly you want to get at the exit - Grundy

1 answer 1

To make a queue (as it turned out, this is exactly what needs to be done), you can do this (recursion):

 '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) { return new Promise((res, rej) => { setTimeout(() => { res(`грузится ${whatIsThisThen}-я пачка артов за ${setRandomTime} мс`); }, setRandomTime); }); }; class Queue{ constructor(data = []){ if(!Array.isArray(data)) data = []; this.data = data; this._processing = false; if(data.length) this.handle(); } handle(){ // Выходим, если больше нет элементов if(this.data.length){ this._processing = true; // Spread'им элементы очередного вызова getNewArts(...this.data.shift()) .then(result => { // Обрабатываем результат console.info(result); // Если данные остались после извлечения, запускаем ещё раз обработку if(this.data.length) this.handle(); else this._processing = false; }); } } add(...data){ this.data.push(data); if(!this._processing) this.handle(); } } let queue = new Queue(); queue.add(getRandom(1400, 2000), 1); queue.add(getRandom(1400, 2000), 2); queue.add(getRandom(1400, 2000), 3); 

  • Yeah, I understood correctly. I myself have already found about .all , but I planned to write an answer tomorrow morning, ahead of it) Thank you. - VostokSisters
  • The only thing for completeness is not enough logic before: the “loading” of images should be done after “loading” json. And you get that he does not participate at all here. True, it easily recovers and the question is not about that. - VostokSisters
  • @VostokSisters, I did not paint the details, because I was not particularly sure that I understood correctly. But the point, I hope, is reported. You are welcome. - user207618
  • Although not, you know, this is not the answer to the question. .all performs promise when all promises are over. Specifically on the question: this is not a consistent implementation of the .then instructions that I described. And according to the logic of my question, I will say that this is illogical, that we load 3 packs of pictures and display all 3 only after they are uploaded. That is, if the 1st pack loaded faster, then it should be removed, but not the rest, if they are not ready. And if the 2 nd load faster, then do not display it until the first one is ready. - VostokSisters
  • one
    @VostokSisters, this is the Spread/rest statement. You can get acquainted here . - user207618