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:
- Assign a function to a property that will be called back later
- Show a KO alert
- 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:
- Assign a function to a property that will be called back later
- Pass that same function to
when
but do not execute it!!!
- Show a KO alert
- 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.