Sambhav Sharma
Sambhav Sharma

Reputation: 5860

SailsJS/NodeJS managing asynchronous nature

I have a code in my controller, that works on an http request, to save a post that user added in the front-end. So I do something like, Model.create(). Now what happens is on the call backs I want to return whether the post was successfully added or not, so that my front-end could show appropriate messages to the user. But the create method works asynchronously. Following is a sample code:

create: function(req, res){

    Activity.create(req.body).done(
            function(err, persistedActivity) {

                    // Error handling
                    if (err) {

                        return res.json({success: false});
                        // The Activity could not be created!
                    } else {

                        return res.json({success : true});
                    }
            }
    );

}

But this code doesn't work because Activity.create() method is async. I have also read about it in other questions or posts. Nothing suggests the exact implementation I am looking for, but it does tell me "don't fight the asynchronous nature of nodejs. It will only hurt later.", and trust me, like everyone else, I don;t wanna get hurt. I essentially need suggestions on how to handle this.

Upvotes: 1

Views: 147

Answers (1)

Jason Kulatunga
Jason Kulatunga

Reputation: 5894

If you wanted to try this with Sails promises, it would look like this:

create: function(req, res){
    Activity.create(req.body)
    .then(function(persistedActivity) {
        return res.json({success : true});
    })
    .fail(function(err){
        return res.json({success: false});
        // The Activity could not be created!
    })
}

I'm not as familiar using SailsJS without promises, but you might want to try using exec instead of done when chaining your create call? I know I've used exec, but I've never used done in that way.

-- Update: It seems that done() is deprecated in favor of exec() so I would definitely try that if you are using 10.x reference

Upvotes: 2

Related Questions