javascriptjquerypromisersvp-promise

Incremental loading of images with promises


I am trying to load same image but with different resolution, one by one, with 1.png first and then 2.png and then 3.png, with help of promises, but when i run the code, it loads only 3.png image, what am i doing wrong?

function loadi(srce){
        if(srce!='3.png'){
        $img1.attr('src',srce).on('load',function(){

            return loadImag();
        });
        }
        else{
            $img1.attr('src',srce).on('load',function(){
                console.log("Load successful");
            });
        }
    }
    function loadImag(){
        return new Promise(function(fulfill,reject){
            fulfill();
        }); 
    }
    loadImag()
            .then(loadi('1.png'),null)
            .then(loadi('2.png'),null)
            .then(loadi('3.png'),null);

New code after 1st suggestion, still facing the same issue, only one image being loaded as seen in chrome dev tools

function loadi(srce){

            return loadImage(srce);

    }

    function loadImage(src) {
        return new Promise(function(resolve, reject) {
            $img1.attr('src',src).on('load',function(error){

                     resolve(); 
            });
// Run image loading logic here
// Call resolve() when loading complete, or reject() when fails.
        });
    }

    loadImage('1.png')
            .then(loadi('2.png'))
            .then(loadi('3.png'))
            .then(function() { 
                console.log('Load successful!'); 
            }) // Not in loadImage().
            .catch(function(err) { 
                        console.log("Error");/* Handle potential errors */
});

Solution

  • Few things wrong with your code:

    Your code should look like this:

    function loadImage(src) {
      return new Promise(function(resolve, reject) {
        // Run image loading logic here
        // Call resolve() when loading complete, or reject() when fails.
      )};
    }
    
    loadImage('1.png')
      .then(function() { return loadImage('2.png'); })
      .then(function() { return loadImage('3.png'); })
      .then(function() { console.log('Load successful!'); }) // Not in loadImage().
      .catch(function(err) { /* Handle potential errors */ });