【发布时间】:2013-09-28 22:14:53
【问题描述】:
在这个问题之前,我已经认为我已经掌握了 JavaScript.. 但不,甚至没有接近:)
我目前正在使用 require.js 进行编程并尝试使用回调创建方法(因为异步 js),但问题是代码在我的 callback(); 调用之后继续执行。 p>
参见以下示例:
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();
这将输出:
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
显然最后两行太多了...我不想要的是在以下场景中进行回调的正确方法..我尝试过:
if (true) {
console.log("Second interval ended.. GOOD");
return callback(true);
}
哪个有效,并且:
if (true) {
console.log("Second interval ended.. GOOD");
return function() {
callback(true);
}
}
这也有效,但对我来说,他们都觉得是错误的解决方案。如何正确地做到这一点?,谢谢!
【问题讨论】:
标签: javascript ajax node.js callback requirejs