The difference between Q.defer () and Promise ()

I am trying to understand why the following code behaves differently with Q.defer () and Promise ()

Case 1 : when I use Q.defer ()

getDocument(id) .then(function (response) { console.log('in first then') return 'from two'; }).then(function (response) { console.log(response) }); var getDocument=function(){ var b = Q.defer(); b.resolve('from getDocument'); // here will do some async operation..this is just an example return b.promise; } 

Exit:

 in first then undefined 

Case 2 : Using Promise ()

 getDocument(id) .then(function (response) { console.log('in first then') return 'from two'; }).then(function (response) { console.log(response) }); var getDocument=function(){ return Promise.resolve('from getDocument'); } 

Exit:

 in first then from two 

Question

  • Why is there a difference in output?
  • I know that Q.defer is an anti-pattern, but then how to choose when to use what?
+6
source share
1 answer

In fact, both examples return the same result (same order). Check this code Example

 var getDocument=function(){ var b = Q.defer(); b.resolve('Q from getDocument'); // here will do some async operation..this is just an example return b.promise; } getDocument(1) .then(function (response) { console.log('Q in first then') return 'Q from two'; }).then(function (response) { console.log(response) }); var getDocumentP=function(){ return Promise.resolve('P from getDocument'); } getDocumentP(1) .then(function (response) { console.log('P in first then') return 'P from two'; }).then(function (response) { console.log(response) }); 

2) Here you can see some use cases of Q.defer: Q.defer that you are doing it wrong

+2
source

Source: https://habr.com/ru/post/1013897/


All Articles