Answer the question
In order to leave comments, you need to log in
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);
});
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);
});
Answer the question
In order to leave comments, you need to log in
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);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question