简体   繁体   中英

Javascript wait for uploading image

In below code I have 3 alert() and I want to these alerts respectively fired. first alert(1) , second alert(2) and then alert(3) but now because of img.onload() function alert(3) fired before alert(2) .

var _URL = window.URL || window.webkitURL;

$("#file").change(function(e) {
var file, img;
if ((file = this.files[0])) {
    img = new Image();
    alert(1)
    img.onload = function() {
         alert(2)
    };
    alert(3)
    img.src = _URL.createObjectURL(file);
}
});

Demo

Is there any way to do this?

Simply use Promise.

var _URL = window.URL || window.webkitURL;

const asyncOnload = img =>
  new Promise((resolve, reject) => {
    img.onload = () => resolve(alert(2))
    img.onerror = () => reject()
  })

$("#file").change(function(e) {
  var file, img;
  if ((file = this.files[0])) {
      img = new Image();
      alert(1)

      asyncOnload(img).then(() => alert(3))

      img.src = _URL.createObjectURL(file);
  }
});

Try it here

Did you try to put the third alert in the onload callback?

var _URL = window.URL || window.webkitURL;

$("#file").change(function(e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        alert(1);
        img.onload = function() {
            alert(2);
            alert(3);
        };
        img.src = _URL.createObjectURL(file);
    }
});

You can try to add function to call back. snippet example:

var _URL = window.URL || window.webkitURL;
$("#file").change(function(e) {
var file, img;
    if ((file = this.files[0])) {
      img = new Image();
      alert(1);
      img.onload = function() {
          alert(2);
          call();
      };
      img.src = _URL.createObjectURL(file);
   }
});

function call(){
    alert(3);
}

Well, there is multiple solutions for your problem. The first obvious one is to call your alert in the img.onload function, like this:

img.onload = () => {
   alert(2)
   alert(3)
}

Or, you can simply use the setTimeout function, but it's more “risky” with slow connection. Hope I fixed your problem 😊.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM