Answer the question
In order to leave comments, you need to log in
[Async and nodejs] Who uses what against callback hell and why?
Good day to all.
After contacting nodejs and choosing it as the basis for a new project, I came across something new and at first very incomprehensible to me, it was asynchrony. All my code was like pyramids of callbacks tending to the right edge of the screen. Over time, I discovered a couple of options for async and Q. I tried to make friends with fibrous, but alas. I heard something about yields and generators, but it also didn’t grow together. I would like to hear your opinion on this issue and find out if there is a panacea?
Thanks, have a productive day.
Answer the question
In order to leave comments, you need to log in
This is a popular problem, everyone is trying to deal with it, they come up with different tools, libraries, and so on. But I will say that with a good architecture, the nesting of functions rarely exceeds 2 pieces - and this is no longer a `hal`. Well, look at the method in which you have this same `hal`. This is a clear violation of S OLID - one method processes data, sends it somewhere, waits for a response in the callback, does something with it, then calls another asynchronous function again and again waits for a response, and so on several times. Therefore, `callback hal` is a cool thing that helps to break the code into independent functions - it accepted the data, did something, sent further both this data and other arguments. Dot.
It was very correctly noted above that you need to break methods into smaller logical parts, and not write sheets, but there is still a problem that you need to make several queries to the database or other external sources, to files, other servers, and then based on all the fragments data received asynchronously, execute business logic and generate a response. Async handles this perfectly, as in the example below.
var dataRequests = [];
// массив запросов к разным данным (БД, файлы, сетевые вызовы)
var dataResults = {};
// я предпочитаю не использовать массив results, который дает async
// а вместо этого делать именованные фрагменты данных
// и писать их в свой хеш
// добавляем один запрос к данным
dataRequests.push(function(callback) {
db.queryRow(
'SELECT * FROM TableName1 where Field1=?', [someValue1],
function(err, res) {
dataResults.firstPiceName = res;
callback(err, null);
}
);
});
// добавляем второй запрос к данным
dataRequests.push(function(callback) {
db.queryValue(
'SELECT count(*) FROM TableName2 where Field2=?',
[someValue2],
function(err, res) {
dataResults.secondPiceName = res;
callback(err, null);
}
);
});
// вызываем массив запросов асинхронно
async.series(dataRequests, function(err, results) {
// тут делаем бизнес-логику над dataResults в котором у нас есть
// все фрагменты данных .firstPiceName и .secondPiceName
// и формируем общий результат
});
I also recommend putting the "node.js" tag on questions about the node.
Well, you listed the main approaches.
Yields, generators, and wrappers over them are the future, but so far they are only available in the 0.11 unstable branch. Fibers is an attempt to emulate them, I don't really like it, and what's the point if generators appear in the stable branch soon? Q and other promises are a good thing, but in js, out of old habit, I use async.
I write current projects in LiveScript , in it such a thing as backcalls helps with sequential asynchronous operations, an example .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question