luciotato / waitfor

Sequential programming for node.js, end of callback hell / pyramid of doom
MIT License
531 stars 29 forks source link

use with on.data #15

Closed mgrant0 closed 9 years ago

mgrant0 commented 10 years ago

I receive a post and then I need to process the data that I get back. In order to read in the post, I have to call:

req.on('data', function(data) {
   body += data;
});
req.on('end', function() {
  post = qs.parse(body)
  // do something with body
}
// now return the updated page

but unfortunately the page gets drawn while the req.on() functions are running, so I thought I would use wait.for as follows:

server = http.createServer(function(req, res){
  wait.launchFiber(handler,req,res);
});

handler = function(req,res) {
  ...
  res.write(page(req))
}

page = function(req) {
  var body = '';
  req.on('data', function (data) {
    body += data;
  });
  var postvars = wait.forMethod(req, 'on', 'end', function () {
    post = qs.parse(body);
    //do something with post
    return(post)
  });

  // now return the updated page, I never get here!
  return(html)
}

My problem is that the wait.forMethod() call never returns. Have I misunderstood something conceptually about how wait.forMethod() works?

luciotato commented 10 years ago

It seems you're misunderstanding wait-for, req.on() and callbacks in general. You do not need wait-for for this case. Are you returning a get from other page on your post? acting like some kind of proxy? You'll need to do something like:

req.on('end', function() {
  res.end( qs.parse(body) );
}
mgrant0 commented 10 years ago

ah hah! Thanks. It took me a few times to look at this to realize and understand what you meant. But yes, of course, you are correct, just call res.end() when I finally have all the result in one place.