Add flow.add() (asyncblok module stuff) inside callbacks on Node.JS

Problem

I'm trying to control my code flow whit the Node.JS module called asyncblock, it uses fibers. I think I'm having some truble to understand it behaviors, this code below doesn't work, the flow isn't waiting..

person.save(function(err){
    if(err) throw err;
    flow.add('goOn');
});
flow.wait('goOn');

But this works well:

person.save(flow.add('goOn'));
flow.wait('goOn');

What I'm doing wrong?

This is the complete code: http://pastebin.com/UCsqPNiF

Problem courtesy of: Alan Hoffmeister

Solution

Here's why your example doesn't work:

The first operation is asynchronous, so the first thing that runs is the flow.wait call. Since flow.add hasn't been called yet, it doesn't actually wait.

Note that your example that works is the correct way to use asyncblock. I'm working on a change to asyncblock that will make it more natural to add tasks asyncronously, but it shouldn't be necessary for this example.

Solution courtesy of: Scriby

Discussion

I can't say I've used asyncblock before, but it looks like add() returns a callback that you will need to execute.

person.save(function(err){
  if(err) throw err;
  flow.add('goOn')(); // Execute the callback!
});
flow.wait(); // wait() takes no arguments.
Discussion courtesy of: loganfsmyth

This recipe can be found in it's original form on Stack Over Flow.