Asif Asif - 1 month ago 15
Javascript Question

Callback mechanism in Javascript

I am trying to understand the callback mechanism in javascript(typescript). If I have a function which expects a callback as input argument, do I have to explicitly use a return statement to hook it up with the actually callback implementation form the calling code OR we can simply have use "callback" reference in the code being called and it automatically hooks up with callback code in the calling code

Code samples (typecript)

// callback code being hooked up using return statement
clear(collectionName: string, callback: any) {
this.getConnection((err, db) => {
if (!db)
return callback(err, null);
db.collection(collectionName).remove();
});
return callback();
}


// callback code being hooked up using reference to reserved callback keyword for automatic hook up with calling code
clear(collectionName: string, callback: any) {
this.getConnection((err, db) => {
if (!db)
return callback(err, null);
db.collection(collectionName).remove({}, callback);
});
}

Answer Source

You don't need to return, you can simply call it like

clear(collectionName: string, callback: any) {
        this.getConnection((err, db) => {
            if (!db)
                callback(err, null);
            db.collection(collectionName).remove();
        });
    return callback();
    }


// callback code being hooked up using reference to reserved callback keyword for automatic hook up with calling code
clear(collectionName: string, callback: any) {
        this.getConnection((err, db) => {
            if (!db)
                callback(err, null);
            db.collection(collectionName).remove({}, callback);
        });
    }