javascript - promise application issue
阿神
阿神 2017-05-16 13:29:18
0
3
375
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!

阿神
阿神

闭关修行中......

reply all(3)
滿天的星座
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

小葫芦
loadImageAsync(url).then(function(img) { doSomething(); }).catch(function(err) { handleError(err); });
我想大声告诉你

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")})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template