Nk SP
Nk SP

Reputation: 862

File APIs Javascript FileReader onload


I am using File APIs with Javascript.
I need to wait for the completation of onload method, how can I do it?

reader.onload = function (e) {
    contents = reader.result;
    var addAttchCallBack = loadRequestExecutor();
    addAttchCallBack.done(function (data) {
        alert("ok");   
    })
};
alert("Ko");

I see always before "Ko"
N.B: the function loadRequestExecutor() correctly returns a promise obj.
Thanks,Nk

Upvotes: 0

Views: 1687

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

You really need to study up on Async behavior and callbacks, then take on understanding promises, as your examples are an odd combination of callbacks and promises, but, to try and explain what is going on in basic terms:

Example 1:

You always seeing KO first, because the first example does this:

  1. Assign a function to a property that will be called back later
  2. Show a KO alert
  3. At some time later the file loads, starts the executor, which on complete (if it ever does) alerts OK

so, basically your onload function will only get called after the file loads (asynchronously), so the alert on the next line gets executed immediately.

Example 2:

You second example, in a comment, is this:

$.when(reader.onload = function (e) {
    contents = reader.result;
    return loadRequestExecutor();
}).done(function (a) {
    alert("ok");
});
alert("KO");

Which translates to:

  1. Assign a function to a property that will be called back later
  2. Pass that same function to when but do not execute it!!!
  3. Show a KO alert
  4. At some time later when the file loads, return the loadRequestExecutor() to the filereader!!!

The end result is not returning the promise to the wait, which is what you probably meant, so it will never work as expected.

Suggestion:

I do not know the plugins that well, but you appear to need to record a promise relating to the load request executor, if that is what you want to wait for.

// Create the loadRequestExecutor and record the promise
var addAttchCallBack = loadRequestExecutor();

// Setup the onload callback  
reader.onload = function (e) {
    contents = reader.result;
    alert("ok - file load is done");   
};

// Listen for the loadRequestExecutor to complete
addAttchCallBack.done(function (data) {
    alert("Ko - loadRequestExecutor is done");
})

alert("I am just an alert that will happen first, as everything above is asynchronous!");

Your overall aim is not clear from the question, so this answer mainly focuses on exampling why your two attempts do not work as you expected.

Upvotes: 1

Related Questions