React - queue for loading pictures with possibility to change it

How can I make a queue for loading pictures in React? In fact, for React VR but in most cases, it should be same for both I think - one bigger difference is probably that I can't use Webpack. Important for me is also that I want to be able to change it during loading. For example, I have 5 really big pictures, we have already loaded first and the second but user click on picture number 4 so instead of 3 it should start loading this one.

1 answer

  • answered 2018-01-11 19:41 Carlo

    One way of handling this kind of asynchronous process is using promises.

    Maybe you have an array of links from which to load the images

    const imagesURLs = [ /* a list of URLs */ ]
    

    You could then do a function that asynchronously retrivers the images

    function loadAllImagesStartingFrom(index, imagesURLS) {
         if (index >= imagesURLS.length) return;
         someImageRetrivingPromise(imagesURLS[index])
             .then(res => {
                /* do something with the image */
                loadAllImagesStartingFrom(index + 1, imagesURLS);
             });
    } 
    

    so where you want to cause all the images to be loaded you could call

    loadAllImagesStartingFrom(0, imagesURLs);
    

    and indipendently call someImageRetrivingPromise when you have to retrive an image if it has not still been loaded (you should make a check first).

    The only problem of this aproach is that if an image have not been loaded and you load it separately then it gets loaded in the "queue" too, so there would be a double call, but you could make a check in loadAllImagesStartingFrom before someImageRetrivingPromise if the image have alredy been loaded then call loadAllImages(index + 1, imagesURLS); instead of the promise.