Promises: how to get a response?

时间:2017-08-13 13:59:39

标签: javascript node.js asynchronous promise

I am in the process of learning Node.js and am stuck on how I return the result of a mysql query as an API response. From what I have read so far, it appears as though I need to return a promise and resolve it, but I am not sure how I can return the data.

function get_free_count() {
    return new Promise(function(resolve,reject) {
        var sql = "SELECT COUNT(id) AS number FROM users";
        conn.query(sql, function(err,result) {
            if(err) return reject(err);
            console.log(result[0].number);
            resolve(result[0].number);
        });
    });
}

app.get('/users/free/count', function(req,res) {
    var output;
    output = get_free_count().then(res.json(output));
});

I am getting stuck at the resolving and returning a response point. If I create a callback function inside the then() function, I am not going to be able to access the res object due to it being out of scope. So far, I haven't been able to find how to return the database value. What are the ways that I can return my free count as an API response?

Thanks in advance.

2 个答案:

答案 0 :(得分:0)

You need to define output inside then callback, also you should call res.json only when promise is resolved. Currently it's called immediately.

app.get('/users/free/count', (req, res) => {
  get_free_count().then(output => res.json(output));
});

答案 1 :(得分:0)

If I create a callback function inside the then() function, I am not going to be able to access the res object due to it being out of scope.

That's where you're wrong - you are able to access res variable, because it still will be in the same scope (what I mean here is that the new, inner scope, can access all variables available in the old, outer scope). There's nothing wrong with the example below:

app.get('/users/free/count', function(req, res){
    // You don't actually need to store the "output" variable,
    // as it serves no real purpose in your example 
    var output;
    output = get_free_count().then(function (dbResult) {
        // req, res, output and dbResult are all valid variables in this scope
        // "dbResult" is equal to "result[0].number",
        // the resolution value of "get_free_count()" call
        res.json(dbResult);
    });
});

This is how closures in JavaScript work, you can read more about them at MDN "Closures"