Skip to content Skip to sidebar Skip to footer

When Should I Use Q.defer And When Just Promise.resolve/reject?

I'm using nodejs and was wondering when should I use Q defer, and when just use Promise.resolve/reject? I saw a lot of examples of both kinds, for example: // with Q defer fucntion

Solution 1:

There is no reason to use the Promise constructor, or - worse - a deferred, when you don't need to. There's nothing asynchronous in your functions, so you don't need (and should not use) callbacks.

Just go for Promise.resolve/Promise.reject or their Q counterparts and construct a promise of a value directly. It's much shorter and simpler anyway.

See also Promise constructor with reject call vs throwing error.

When is a good practice to use defer?

Never. Even in Q, you should use Q.Promise.

Is there any difference between Promise (native) and Q? They look different when I look at the return value in node console.

Well, they're different classes, with different properties, and Q promises do have more methods. They do work the same though, and are completely interoperable with each other.

Post a Comment for "When Should I Use Q.defer And When Just Promise.resolve/reject?"