javascript - Difference between callback hell and nested promises -


i started working nodejs , mongodb(using monk). when came across term "callback hell". in code doing same thing. example-

dbcall(d1, function(e, docs){  if(docs.length!=0)   dbcall(d2, function(e, docs1){    if(docs1.length!=0)     dbcall(d3, function(e, docs2){       //doing docs,docs1,docs2     })    })  })  

this when started reading on "promises", , came across article - https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/

since needed both docs , docs1 inside third callback used nested promises.

dbcall(d1) .then(function(docs){   if(docs.length!=0)    return dbcall(d2)    .then(function(docs1){      if(docs1.length!=0)       return dbcall(d3)       .then(function(docs2){         //doing docs,docs1,docs2       })     })   }) 

from above code snippet have following questions(/doubts) :

  1. apart making code more readable, promises have performance benefits?
  2. nesting promises , callback hell looks similar me. there difference?

i new concept of promises. appreciated.

apart making code more readable, promises have performance benefits?

probably not.

nesting promises , callback hell looks similar me. there difference?

promises don't automatically prevent callback hell. because more flexible "simple" callbacks, can composed in different ways, makes easier avoid callback hell.


since needed both docs , docs1 inside third callback used nested promises.

sometimes nested promises unavoidable. however, there no need nest them if don't have executed sequentially. execute them in parallel:

promise.all([  dbcall(d1),  dbcall(d2),  dbcall(d3) ]).then(function(docs) {   // docs array: [docs, docs1, docs2] }); 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -