Reputation: 862
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
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:
You always seeing KO
first, because the first example does this:
so, basically your onload
function will only get called after the file loads (asynchronously), so the alert
on the next line gets executed immediately.
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:
when
but do not execute it!!!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