Skip to content Skip to sidebar Skip to footer

Making A Javascript Function Async With Callback

Previously I had MyClass.prototype.method1 = function(data1) { return this.data111.push(data1); }; MyClass.prototype.method2 = function(i) { var data = this.method1(i)

Solution 1:

Just pass on the callback:

MyClass.prototype.ended = function(callback) {
    this.getState("end", callback);
};

You should do this in your other functions too and I'd suggest to stick to one interface. I.e. either return the value directly (if possible) or use callbacks.


Solution 2:

Only those methods that do asynchronous tasks need callback style. There is no reason to use it for method1, method2 and method3.

getState now is the actual asynchronous method. Using ajax/setTimeout/whatever is quite obvious in here. Yet, I can spot one mistake: The callback call should always be the last statement, just as you won't do anything after a return statement. Even though you can, better call back after setting the internal options object:

                …
                oldThis._options.afterGetState(key, value);
                callback(value, oldThis);

Now, the ended method. Since it uses the async getState, it will become asynchronous itself and you need to use callback style (notice that getState() will not return the value). So you will call getState, and when that calls back you will transform the result and pass it to your own callback:

MyClass.prototype.ended = function(callback) {
    this.getState("end", function ownCallback(state) {
        var result = !!state; // or whatever you need to do
        callback(result);
    });
};
// and if you don't need to do anything with the result, you can leave out ownCallback:
MyClass.prototype.ended = function(callback) {
    this.getState("end", callback);
};

Post a Comment for "Making A Javascript Function Async With Callback"