user796443
user796443

Reputation:

having a bit of a trouble with promises in nodejs

Forgive my noobiness, but how do I rewrite these with promises?

I read mongoose supports promises. Not sure about social, but console.log shows me it returns object, so that must be it?

mongoose.connect('mongodb://localhost/trends');

social.facebook(urlValue, function(err, signals) {
  console.log(signals);
});

var articleData = Article({
  publisher: urlValue,
  url: urlValue
});

articleData.save(function(err) {
  if (err) throw err;
  console.log('Url saved successfully!');
});

Upvotes: 0

Views: 25

Answers (1)

mfred
mfred

Reputation: 187

If you use mongoose v4.x, articleData.save() returns a promise (cf http://mongoosejs.com/docs/promises.html).

Your code would become:

articleData.save()
    .then(function(doc) {
        console.log('Url saved successfully!');
    })
    .catch(function(err) {
        // Here is where you should deal with the error
    });

Upvotes: 2

Related Questions