Before this question, I already thought that I had mastered JavaScript.. but no, not even close :)
I'm currently programming with require.js and trying to make methods with callbacks (because of async js) but the problem is that code continues execution after my callback(); calls.
See following example:
var Second = function () {
console.log("Second init");
};
Second.prototype.load = function (callback) {
console.log("Second load");
var timeOut = setTimeout(function () {
clearTimeout(this);
if (true) {
console.log("Second interval ended.. GOOD");
callback(true);
}
console.log("Second interval ended.. NO, YOU SHOULD NOT BE HERE!");
callback(false);
}, 1000);
};
var First = function () {
console.log("First init");
var second = new Second();
second.load(function (returned) {
console.log("Second returned: " + returned);
});
};
First();
This will output:
First init
Second init
Second load
Second interval ended.. GOO
Second returned: true
Second interval ended.. NO, YOU SHOULD NOT BE HERE!
Second returned: false
Where obviously two last lines are too much... What I would want't is a proper way to do callback in following scenarion.. I tried:
if (true) {
console.log("Second interval ended.. GOOD");
return callback(true);
}
Which works, and:
if (true) {
console.log("Second interval ended.. GOOD");
return function() {
callback(true);
}
}
Which works too, but both of them feels like wrong solutions to me.. how to do this correctly?, thanks!