简体   繁体   English

nodejs/pg,回调参数

[英]nodejs/pg, callback parameters

I am fairly new to node.js, and haven't done much of javascripts.我对 node.js 相当陌生,并没有做过很多 javascripts。 Tried to search my problem, but couldn't find specific answer related to it.试图搜索我的问题,但找不到与之相关的具体答案。

So, while I was working on attaching the PostgreSQL to my app, I followed a snippet from some example on web, and it seems like working pretty well.因此,当我将 PostgreSQL 附加到我的应用程序时,我遵循了网络上一些示例的片段,看起来工作得很好。

Anyways I wanted to understand how it works, I had a problem understanding specific part of the following code:无论如何,我想了解它是如何工作的,但我在理解以下代码的特定部分时遇到了问题:

module.exports = {
  query: function(text, values, cb) {
    pool.connect(function(err, client, done) {
      if(err) {
        return console.error('error fetching client from pool', err);
      }

      console.log(client);

      client.query(text, values, function(err, result) {
      done();
      cb(err, result);
      })
    });
  }
}

and the specific part is:具体部分是:

pool.connect(function(err, client, done) { ... } pool.connect(function(err, client, done) { ... }

What I understood is connect function takes callback function with err, client, and done as parameter, however I couldn't understand from where the function(err, client, done) is passed to connect function as parameter .我所理解的是 connect 函数采用带有 err、client 和 done 的回调函数作为参数,但是我无法理解从哪里将 function(err, client, done) 作为参数传递给 connect 函数 By where, I mean an object or a caller that call connect function.这里,我的意思是一个对象或一个调用连接函数的调用者。

I had suspected that it would be handled internally, but I wanted to know clearly.本来就怀疑会在内部处理,但是想清楚的知道。

Bydefault all callback function, the first parameter must be an error and second will be a result of ur callback function.默认所有回调函数,第一个参数必须是错误,第二个参数是回调函数的结果。

Done is similar to callback keyword, which says, your task is over and give response back from where the function has called, its just like return statement in normal function Done 类似于 callback 关键字,它表示您的任务结束并从函数调用的地方返回响应,就像普通函数中的 return 语句

example:例子:

 function callbackDemo(arg1, arg2, callback) {
  if (condition)
    callback(null, "Success");
    else
    callback("error");  
   }

callbackDemo(1, 2, function(err, result){

  if(!err)
    console(result);
   else
    console.log(err);
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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