0

I just get interest in node.js.

If everything is execute "non-blockingly", when does it flush the result to the client(browser), if I want to get result from db, post to other server, and return the result get from other server, do I need to put callback inside a callback like this?

var dbquery = db.query(function(result){
    var postToServer = otherServer.post(result.id,function(networkResult){
           render(networkResult)
    })

})

Or can be handle "more gracefully"?

Alvar
  • 529
  • 5
  • 18
  • I prefer to use callback's, because synch task sometimes freezes browser. – Michał Szałapski Aug 29 '13 at 22:57
  • Note: Using or repeating tags in the title [should be avoided](http://stackoverflow.com/help/tagging), which is why [Andy G edited](http://stackoverflow.com/posts/18522229/revisions) to remove it. – Jonathan Lonowski Aug 29 '13 at 23:09
  • _"The only time you should use tags in your title is when they are organic to the conversational tone of the title"_, which is exactly the case here. – cababunga Aug 29 '13 at 23:14
  • @cababunga Maybe. But, it's still redundant with the `node.js` tag already applied to the question. – Jonathan Lonowski Aug 29 '13 at 23:15

2 Answers2

0

This is exactly what promises are for. There are few libraries implementing them in JavaScript.

https://github.com/kriszyp/node-promise http://howtonode.org/promises

It's a bit too much to explain here, so you have to go read and look at some sample code.

Basically you code will look like this:

query_db()
.then(function (result) { return otherServer.post(result.id); })
.then(function (networkResult) { render(networkResult); });
cababunga
  • 3,090
  • 15
  • 23
0

Use a library, something like https://github.com/kriskowal/q (promises) or https://github.com/caolan/async.

Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109