Taku
Taku

Reputation: 5927

Applying variables in a function from private function - Node.js

I am using Node.js with bluebird and am trying to use defaultMySQLOutput as a model for output as such:

function defaultMySQLOutput(err, result){
    return err ? reject(err) : resolve(result);
}

function something(){
    return new Promise(function(resolve, reject){
        mysql.query(q, defaultMySQLOutput);
    });
}

but this does not work. The error says "resolve is undefined", but when I do

mysql.query(q, function(err, results){
    resolve(results);
});

it works.

I've also tried,

defaultMySQLOutput.call(this, err, results)

and

(new defaultMySQLOutput)

but unable to make it happen. Is there a way to make this work? Any reference would be appreciated.

Thanks in advance.

Upvotes: 1

Views: 26

Answers (1)

GregL
GregL

Reputation: 38131

You can use the power of closures to create a new function that will have access to resolve and reject correctly:

function defaultMySQLOutput(resolve, reject) {
    return function (err, result) {
        return err ? reject(err) : resolve(result);
    }
}

function something(){
    return new Promise(function(resolve, reject){
        mysql.query(q, defaultMySQLOutput(resolve, reject));
    });
}

Upvotes: 2

Related Questions