Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing "blocking" code in nodejs

Tags:

Everything in nodejs is non-blocking which is nice, but how would I go about making function alls that have to be one after the other without having a huge nested list of callbacks?

like image 578
AdamB Avatar asked Mar 20 '11 02:03

AdamB


2 Answers

You don't have to nest your callbacks.

There are many patterns in writing asynchronous code.

For instance, this matrioska-nested-style...

database.find('foo', function (err, data) {
  database.update('foo', 'bar', function (err, data) {
    database.delete('bar', function (err, data) {
      console.log(data);
    });
  });
});

... can be rewritten in a cleaner (but more verbose) way:

var onDelete = function (err, data) {
      console.log(data);
    },

    onUpdate = function (err, data) {
      database.delete('bar', onDelete);
    },

    onFind = function (err, data) {
      database.update('foo', 'bar', onUpdate);
    };

database.find('foo', onFind);

Another option is using a module to abstract serial and parallel execution of callbacks.

like image 111
masylum Avatar answered Sep 21 '22 06:09

masylum


Use Step.

It's "a simple control-flow library for node.JS that makes parallel execution, serial execution, and error handling painless".

like image 33
Chetan Avatar answered Sep 20 '22 06:09

Chetan