Ahmed Shamel
Ahmed Shamel

Reputation: 1962

How to return array after loading multiple images?

I work on application that made some image processing on the loaded images, and if the some condition occur, it will return true and if not it return false.

This is my code:

function LoadImages(fi) {
    var status = new Array();

    for (var i = 0; i < fi.length; i++) {
        var fr = new FileReader;
        fr.onloadend = (function (str) {
            if (typeof str === "object") {
                str = str.target.result; // file reader
                var img = new Image();

                img.onload = (function () {
                    if (some_coditions)
                        status.push(true);
                    else
                        status.push(false);
                });
                img.src = str;
                ImgNam.push(str);
            }
        })
        fr.readAsDataURL(fi[i]);
    }
    return status
}


$("#Images").change(function () {
    var fi = $(this)[0].files;
    var status = LoadImages(fi);
});

In html :

<input id="Images" type="file" multiple />

I want to get the status array. The problem is that the function LoadImages return the value before the load complete. I know the reason why this happen, but I don't know how to solve it.

Upvotes: 3

Views: 289

Answers (1)

Dan Prince
Dan Prince

Reputation: 29989

You can't return any values that you are getting asychronously, because the function will have already returned by the time fr.onloadend is called. However, you can return a Promise, rather than an array:

function LoadImages(fi) {
  var deferred = new Promise(function(resolve, reject) {
    var status = [];
    // do some asynchronous work, like putting images into an array
    // ...
    // when you are ready to return, call resolve with your return value
    resolve(status);
  });

  // return the promise
  return deferred;
}

Then rather than expecting a return value, you would write:

var fi = $(this)[0].files;
LoadImages(fi).then(function(status) {
  // use status here.
});

Upvotes: 5

Related Questions