Colin
Colin

Reputation: 4135

How do I properly issue response to post when waiting for async method to complete?

Here's the setup in a module. See, esp., comments marked by ****:

exports.saveWall = function (req, res) {
    var status;

    mongoClient.connect(connectionString, function (err, db) {
        if (err) { return console.dir(err); }

        db.collection(pictureWallsCollectionName).insert(
            { _id: req.body.wallId, pictures: req.body.pictures }, 
            function (err, res) {   
                db.close();
                if (err) {
                    status = 500;
                    console.dir(err);
                }
                else {
                    status = 200;
                    //*****can't do this here, because res is out of scope!
                    res.status(status).send(http.STATUS_CODES[status])
                    console.log('Inserted into the ' + pictureWallsCollectionName + ' collection');                     
                }
            });      
    });

    //*****can't do this yet because the above isn't done.
    res.status(status).send(http.STATUS_CODES[status])
}

I basically want to call the line res.status(status).send(http.STATUS_CODES[status]) in my callback, but I can't because res.status is null at that point.

All I want to do is respond to a POST, but I am not getting anywhere.

Upvotes: 1

Views: 101

Answers (2)

snollygolly
snollygolly

Reputation: 1886

Even though you solved your scope issue (which is awesome), nesting callbacks can get kind of tricky quickly (as you saw). A good way to deal with this is to use promises. The two main packages for promises are Q and Bluebird (with Bluebird being my favorite).

You can also use a package that has already promise-ified mongo calls for you, like promised-mongo

Once you have that all set up, it's just a matter of chaining .then for successive steps, and then sending your response when the promise is resolved.

For a specific example, check out this answer and see if that helps.

Upvotes: 1

Colin
Colin

Reputation: 4135

Ugh...

It turns out my issue was that "res" was defined both here:

exports.saveWall = function (req, res) {

...and here:

db.collection(pictureWallsCollectionName).insert(..., 
        function (err, res) {

...so it turns out I could call "res" all along, I was just trying to call the wrong "res" because it got redefined.

On a side note, f*** you, javascript!

Upvotes: 1

Related Questions