简体   繁体   中英

Is it not necessary for a callback method to have a definition in node.js?

I am new to node.js. I have been seeing code where a callback method is just called but it is never defined anywhere in the file. So without definition what does that call to the callback method do exactly? For example

CollectionDriver.prototype.findAll = function(collectionName, callback) {
this.getCollection(collectionName, function(error, the_collection) { 
  if( error ) callback(error);
  else {
    the_collection.find().toArray(function(error, results) { 
      if( error ) callback(error);
      else callback(null, results);
    });
  }
});

};

I understand that based on the success or failure of the this.getCollection(collectionName) method, the callback method "callback" is called appropriately, however there is no definition available for the callback method. So how is this call useful?

The callback argument is passed when findAll() is called. It is up to the caller to define it appropriately and pass a reference to it. This is a characteristic of Javascript, so it's not just node.js.

You should see something like this in the calling code:

var driver = new CollectionDriver(...);
driver.findAll("foo", function(err, results) {
    if (err) {
        console.log(err);
    } else {
        // process results here
    }
});

Here, the callback is defined by the caller and passed to the findAll() method.


It also doesn't have to be an inline function definition like above. The caller could also be like this:

function findCallback(err, results) {
    if (err) {
        console.log(err);
    } else {
        // process results here
    }
}

var driver = new CollectionDriver(...);
driver.findAll("foo", findCallback); 

In either case, you're passing a reference to a function to .findAll() which it calls when it completes.

callback is a parameter to findAll ( function(collectionName, callback) !). You would use it like so:

// assuming `driver` is an instantiated `CollectionDriver`:
driver.findAll("collectionOfCows", function(error) {
  console.log("findAll called us back with", error);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM