Reputation: 3510
I've hopefully a quick question for someone with a bit more knowledge than I.
If I have code in a Node api implementation which basically creates an entity and saves it directly to MongoDB using Mongoose, do I need to wrap all that in an promise library to get it as asynchronous as possible? Or will the implementation of the Mongoose/MongoDB Node libraries already do their work in an async fashion, so that my only overhead on the message pump is the object creation.
The code below is what we have in the API, it creates the promise below and executes it, I'm just wondering if the overhead of the promise is actually worth it if the Mongoose/MongoDB libraries are async anyway.
Hope all that makes sense.
function action(promise) {
var date = new Date(),
taskWorkQueue = new TaskWorkQueueModel({
"TaskId": taskid,
"metadata": metadata,
"State": 0,
"TaskType": taskType,
"ApplicationName" : token.ApplicationName ,
"dateEntered": date});
taskWorkQueue.save(function (err) {
if (err)
{
promise.reject(err);
}
else
{
promise.resolve(taskWorkQueue);
}
});
Upvotes: 1
Views: 159
Reputation: 23060
That is not the reason to wrap these things in a promise. All of the good node libraries (like Mongoose) are already asynchronous. Using a promise just gives you an alternative way to write your code instead of using callbacks.
Take a look at the documentation for q, they show an example of what kind of difference in coding style you can expect from promises versus callbacks.
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});
versus
Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
// Do something with value4
})
.catch(function (error) {
// Handle any error from all above steps
})
.done();
It's also worth mentioning that mongoose already supports promises via mpromise, and you shouldn't need to wrap them yourself. There are also libraries available which use other promise frameworks around mongoose like mongoose-q.
Upvotes: 3