How to load images async with RxJs and perform a method when all loaded

前端 未结 6 909
臣服心动
臣服心动 2020-12-30 10:25

I am trying to convert my promise based code to RxJs but have a hard time to get my head around Rx especially RxJs.

I have a an array with paths.

var         


        
6条回答
  •  长发绾君心
    2020-12-30 10:33

    I don't think you can do that easily with observables, as there's nothing there to indicate a finish (unless you have an initial size). Look at the other answers for the Rx version.

    However, you can use an array of Promises:

    /**
     * Loads an image and returns a promise
     * @param {string} url - URL of image to load
     * @return {Promise} - Promise for an image once finished loading.
     */
    function loadImageAsync(url) {
        return new Promise(function(resolve, reject) {
            var img = new Image();
            img.src = imagePath;
            image.onload = function() { resolve(img); };
            image.onerror = reject;
        });
    }
    

    And with that, you can easily do something like this:

    var imageUrls = ['url1', 'url2', 'url3'];
    Promise.all(imageUrls.map(loadImageAsync))
        .then(function(arrayOfImageElements) {
            // All done!
        });
    

提交回复
热议问题