0

I have to store some images, I'm taking the value like this:

var imgGaleria1 = $("#imgGaleria1")[0].files[0];
var imgGaleria1Blob;

if (imgGaleria1) {
    var reader = new FileReader();
    reader.onload = function (e) {
        reader.readAsDataURL(imgGaleria1);
        imgGaleria1Blob = e.target.result;
    };
}

But obviously I can't store into imgGaleria1Blob, because reader is just async task, I searched that I need to do a promises that returns y value to store it, but I don't understand how promise works.

Can someone explain to me how can I execute this code into a promise and store the result (e.target.result)?

Thanks for the help guys.

Samurai
  • 3,724
  • 5
  • 27
  • 39
Nega developer
  • 259
  • 3
  • 8
  • 19
  • You could use a callback, but you already have one, the callback to the onload event handler. Using promises won't really help you get access to things before they are loaded, it just makes it easier to move things out of the callback, and still wait for the event to happen. – adeneo May 24 '15 at 19:28

1 Answers1

0

I need to do a promises that returns my value to store it

Promises don't return values, they "contain" them - a promise is a wrapper that represents an asynchronous value, a pointer to the future.

but I don't understand how promise works

You definitely should go for that before applying them to your code. You will find some good resources here or at https://www.promisejs.org/.

how can I execute this code into a promise and store the result?

Have a look at How do I convert an existing callback API to promises? for the generic approach. For jQuery, you will construct a Deferred object that you can later resolve, and can immediately get a promise for that future value from.

var dfd = $.Deferred();
var reader = new FileReader();
reader.onload = function(e) {
    dfd.resolve(e.target.result);
};
reader.readAsDataURL(imgGaleria1);

promiseForImgGaleria1Blob = dfd.promise();

You will later be able to consume that value via

promiseForImgGaleria1Blob.then(function(imgGaleria1Blob) {
    // use the blob here
});

but notice that everything that depends on this value is asynchronous, and should become a promise-returning function now.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Wow, thx for all, this worked for me and u help me to understand something more how promise works.. i will pay more attention about how their works. – Nega developer May 24 '15 at 22:20