Callback as return of argument

Asked

Viewed 421 times

1

My question is this, from what I understand callbacks are functions passed as parameter that will be executed when some instruction is performed, but I often see the callback as a reserved word to return parameters to a function, as in the example below:

function run(textQuery, callback)
{
    const sql = require('mssql');
    var callbackDone = false;    
    const connectionPool = new sql.ConnectionPool(config, err => {   
        connectionPool.request()
        .query(textQuery, (err, result) => {            
            sql.close();
            callbackDone = true;
            callback(err, result);
        })    
    })    
    connectionPool.on('error', err => {        
        sql.close();
        if(!callbackDone)
        {
            callback(err, null);
        }
    })
}   

Could you explain to me how this works ?

1 answer

0


That one question covers much about the concept of callback. The difference to what you scored is that you can pass the callback as a function parameter when the return function needs additional parameters (most often a missing value). I will illustrate:

function handler(err, res, message){
    // message é o parametro que estava faltando
    console.log(err, res, message);
}

function run(textQuery, callback){
    callback(null, [], "Success");
}

run("", handler);
  • Using your example, if I understand correctly, the word 'callback', in this case, is being used to complete the request for parameters required by the Handler function that was passed as a parameter to run function?

  • In fact is passing what is callback function, is a @B.Days reference

  • 1

    Wow, I get it, now that it’s all clear this up pretty obvious kk, thanks for the help @Lucas Costa

Browser other questions tagged

You are not signed in. Login or sign up in order to post.