Search code examples
javascriptnode.jspromisepg

nodejs pg-promise get variable outside function scope


Relatively new to working with promises. Right now, I'm running the following in order to query some data from the database. I understand that the function is async, thus everything within the "then" gets executed sometime later when the query finishes, passing the results into that function. What I don't understand is how to access variables scoped to the outside function such that I can use them?

var db = require('../repositories/db.js');
var Response = require('../models/responseModel.js');

var dashboard = {};

dashboard.getCompany = function (req, res) {
    var companyId = req.params.companyId.toUpperCase();
    var sql = db.getSql('./sql/getCompany.sql');

    db.any(sql, { tic: companyId })
        .then(function (data) {
            var r = new Response(true, 'retrieved company', data);

            // can't do this because companyId is undefined...            
            // console.log(companyId);

            res.status(200)
                .json(r);
        })
        .catch(function (err) {
            var r = new Response(false, err.message);
            res.send(r);
        });
};

Been reading up on pg-promise as well as bluebird (that's what I've initialized my promise library with...), but I'm not quite getting it :( I just need to be able to access variables outside my query, either by somehow passing them into the .then() function, or some other way. In the example above, how can I access some ID that's passed in the req.params but inside query?

Any help would be appreciated.


Solution

  • A great option is to use Promise.bind();

    Here's an example of 3 functions, a, b, and c. C needs the return values of A and B, but b does not need to know what a returns (this is contrived).

    var Promise = require('bluebird');
    
    function a (){
        this.p1 = 'hello';
    }
    function b (){
        this.p2 = 'goodbye';
    }
    
    function c (){
        return this.p1 + this.p2;
    }
    
    Promise.bind({})
        .then(a)
        .then(b)
        .then(c)
        .then((res)=> console.log(res))
        .catch(err => console.log(err));
    

    This returns:

    hellogoodbye

    The object that you hand to Promise.bind() can be any object you like. So you can put your external variables on the object and they will be accessible via this. Bind takes the object handed to it and assigns it to this for all functions chained off of the promise.