search

Home  >  Q&A  >  body text

javascript - promise application issue

function loadImageAsync(url) {
  return new Promise(function(resolve, reject) {
    var image = new Image();

    image.onload = function() {
      resolve(image);
    };

    image.onerror = function() {
      reject(new Error('Could not load image at ' + url));
    };

    image.src = url;
  });
}

What I want to know is how to use this method? I entered URL, and then obtained the object image in then? But I tested it, but there was no response!

阿神阿神2753 days ago373

reply all(3)I'll reply

  • 滿天的星座

    滿天的星座2017-05-16 13:31:18

    loadImageAsync('./img/news-1.png').then((img) => {
        document.getElementById("app").appendChild(img)
        console.log(img)
    })

    When called like this, the parameter of then is the parameter of resolve, which is the image object. The function can be realized by appending this object to p

    This is the final result

    This is the console

    reply
    0
  • 高洛峰

    高洛峰2017-05-16 13:31:18

    loadImageAsync(url).then(function(img) { doSomething(); }).catch(function(err) { handleError(err); });

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-16 13:31:18

    Yes, I tried it in the browser:

    function loadImageAsync(url) {
      return new Promise(function(resolve, reject) {
        var image = new Image();
    
        image.onload = function() {
          resolve(image);
        };
    
        image.onerror = function() {
          reject(new Error('Could not load image at ' + url));
        };
    
        image.src = url;
      });
    }
    
    loadImageAsync('https://www.baidu.com/img/bd_logo1.png').then(function(){alert("jiazai wancheng")})

    reply
    0
  • Cancelreply