Reputation: 8506
Below is my code
var uploadIDImage = {
IDPos: {},
IDNeg: {}
};
var FR = new FileReader();
FR.onload = function(e) {
console.log("123");
console.log(e);
$("#UploadIDPos img").remove();
$("#UploadIDPos i").hide();
$('#UploadIDPos').prepend('<img id="IDPosImg" style="width: 140px; height: 80px;"/>');
var img = document.getElementById('IDPosImg');
img.src = FR.result;
uploadIDImage.IDPos.Files = FR.result.split(",")[1];
console.log("11111");
};
if(e.target.files[0]) {
FR.readAsDataURL(e.target.files[0]);
if(originalIDPosSize === undefined) {
var size = Math.round(e.target.files[0].size / 1024 / 1024);
originalIDPosSize = size;
}
else {
totalSize = totalSize + originalIDPosSize;
var size = Math.round(e.target.files[0].size / 1024 / 1024);
}
var remainSize = totalSize - size;
console.log("Remain size : " + remainSize);
$("#remain-size").text(totalSize - size);
totalSize = remainSize;
}
console.log("22222");
console.log(uploadIDImage.IDPos.Files);
What I got from my console.log is first print "22222" and undefined and then "111111".
Why "11111" not print first?
Upvotes: 1
Views: 1662
Reputation: 9416
Your section of code FR.onload = function(e) { ... }
is just defining a handler for the FR
object. The FileReader
methods like readAsDataURL()
are asynchronous -- your program continues after it executes the FR.readAsDataURL(...)
statement.
Then later, when the file reading is done, then the function you specified for FR.onload
runs. It is indeterminate whether this happens before or after your console.log("22222");
statement.
Upvotes: 2
Reputation: 33000
When you do
FR.onload = function(e) {... }
you are setting a callback on the FileReader
which is called when the reading operation has successfully completed.
Now you script proceeds and runs console.log("22222");
After a while the callback is invoked and you see the 11111
.
Upvotes: 5