Can someone explain how callbacks are invoked in Node.js please?

时间:2019-04-05 15:52:14

标签: javascript node.js asynchronous callback

I understand callback functions conceptually, but I don't understand how they are understand in Node.js and am quite confused by the syntax. Can someone give me a simple explanation for each line of code which is running? The code works, but I don't understand why.

var removeById = function(personId, done) {
  Person.findByIdAndRemove(personId, function(err, data) {
    if(err) {
      done(err); 
    }
    done(null, data);
 });
};

Line by line explanation.

2 个答案:

答案 0 :(得分:0)

第1行(假设)

var removeById = function(personId, done) {

donecallback的正式标识符,稍后当您调用removeById函数时会通过

第2行

Person.findByIdAndRemove(personId, function(err, data) {

findByIdAndRemove期望第2个参数是一个具有两个参数的函数,第一个err,将保留错误,第二个data,将保留数据/结果

第4行

done(err)

第6行

错误呼叫您的回调

done(null, data)

使用第一个参数为null(可能表示没有错误)和data来调用回调,它将保存数据/结果

附加说明:

您传递给removeById的回调也应该(最好是,如果您不对其做任何其他事情)期望2个参数,与传递给findByIdAndRemove的回调相同

答案 1 :(得分:0)

Person.findByIdAndRemove基本上类似于:

Person.findByIdAndRemove = function(personId, callback) {
  // The code is executed 
  // call function on error | success
  callback(err, data);
};

您要执行的回调应类似于:

const done = function(err, data) {
  if(err) {
   console.log(err); 
  }
  console.log(data);
}

您的代码:

var removeById = function(personId, done) {
  Person.findByIdAndRemove(personId, function(err, data) {
    if(err) {
      done(err); 
    }
    done(null, data);
 });
};

用法:

removeById(3, done);