S
S
Sirian2012-09-12 17:01:26
JavaScript
Sirian, 2012-09-12 17:01:26

Node.js: callback or deferred?

worked a little in node.js and decided to ask the community - which approach is better to use: callback or deferred?

Actually an example with callback:

var f1 = function(callback) {
    setTimeout(function() {
        callback(null, 'f1 done');
    }, 100);
};

var f2 = function(callback) {
    f1(function(err, data) {
        if (err) {
            callback(err);
            return;
        }
        // работает с data
        callback(null, 'f2 done');
    })
};

f2(function(err, data) {
    if (err) {
        //....
        return;
    }
    console.log(data);
});


Cons:
1. I need to parse err many times. (essentially in every function).
2. in a good way, you need to not just call callback(null, data); and additionally check typeof callback === function, which also introduces additional complications

. The second approach is to use deferred (for example, jquery)
var $ = require('jquery');
var f1 = function(callback) {
    var d = $.Deferred();
    setTimeout(function() {
        d.resolve('f1 done');
    }, 100);
    return d.promise();
};

var f2 = function() {
    return f1().pipe(function(data) {
        // работает с data
        return 'f2 done';
    });
};

f2().done(function(result) {
    console.log(result);
});


The plus is obvious - we can only process the successful execution of f1 in f2, and pass the error further and no troubles with checking typeof callback

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew D.Laptev, 2012-09-12
@agsh

If I correctly understood the question, how convenient it is to build a chain of functions that call themselves through callbacks and pass data to the next function, then using async it is written like this:

var async = require('async');

async.waterfall([
  function(callback){
    setTimeout(function() {
      console.log('f1 done');
      callback(null, 'data from f1');
    }, 100);
  },
  function(data, callback){
    // работа с data
    // или расширение цепочки через функцию f3, которая по окончании работы вызовет callback
    // f3(callback);
    console.log('f2 done');
    callback(null, 'done');
  }
], function (err, result) {
  // result now equals 'done'
  if (err) {
    // единое место для отлова ошибок
  }
  console.log(result);
});

A
Andrew D.Laptev, 2012-09-12
@agsh

For such cases, I use async myself .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question