1

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!

4

2 回答 2

5

这可能是一个意见问题,但return callback()通常是标准。您可以在 Node 源代码中看到它以这种方式使用。来自文件系统模块的示例:

fs.fstat(fd, function(er, st) {
  if (er) return callback(er);
  size = st.size;
  if (size === 0) {
    // the kernel lies about many files.
    // Go ahead and try to read some bytes.
    buffers = [];
    return read();
  }

  buffer = new Buffer(size);
  read();
});
于 2013-09-28T22:15:57.467 回答
0

如果您不想在调用回调后执行代码,请不要在此处放置任何代码。console.log如果您在调用回调函数后没有放置语句,则不会发生任何事情:您的函数将简单地返回。

于 2013-09-28T22:21:24.840 回答