Understanding callbacks in node

I am starting in nodejs. I am trying to understand a bit of code. This basically creates an event.

models / event.js

EventSchema.static("createEvent",function(event,user,callback){
var That = this;

async.waterfall([
    function(callback){
        var time = moment(event.releaseTime).tz(event.releaseTimezone).utc().toDate();
        event.rTime= time;
        callback();
    },

    function(callback){
        var model = new That(event);
        That.validateEvent(model,user,function(err){
            if(err){
                callback({message:err});
                return;
            }else{
                callback(null,model);
                return;
            }
        });
    },

    function(model,callback){
        model.save(function(err,doc){
            if(err){
                callback({message:"Error saving event",err:err});
            }else{
                callback(null,doc);
            }
        });
    },

    function(savedEvent,callback){ /*Some further code is written here*/}

I understood the first two callback functions, but did not understand the third and fourth.

The second callback says

callback(null,model);

and then the next callback starts with

function(model,callback){

The third callback says

callback(null,doc);

and then the next callback starts with

function(savedEvent,callback){

I do not understand this. Any help is appreciated.

+4
source share
2 answers

With a waterfall, the first argument (s) of the second and subsequent functions is / - the return value from the previous callback. On docs :

waterfall([
  function(callback){
    callback(null, 'one', 'two');
  },
  function(arg1, arg2, callback){
    callback(null, 'three');
  },
  function(arg1, callback){
    // arg1 now equals 'three' 
    callback(null, 'done');
  }
], function (err, result) {
  // result now equals 'done' 
});
+1
source
callback(null,model);

( callback). ( null model) .

function(model,callback){

. . model. callback.


.

+2

Source: https://habr.com/ru/post/1693644/


All Articles