Ahmed Ahmed - 21 days ago 6
Node.js Question

How to avoid callback hell after one AJAX call

I have a nodeJS application that requests data from an API once. I then want to do some processing on this data by using separate functions. However, since the AJAX is asynchronous, I'm forced to use async as follows:

async.series(
[
function(callback) { getContentFromAPI("banana",callback); },
function(callback) { doSomeProcess1(callback); },
function(callback) { doSomeProcess2(callback); },
function(callback) { doSomeProcess3(callback); },
function(callback) { doSomeProcess4(callback); },
]
);


Is there any way this can be done better? I'm only requesting one asynchronous process and want to avoid using async since all the other processes are sync.

What should I do?

Answer

However, since the AJAX is asynchronous, I'm forced to use async as follows

you've overcomplicated a very simple and common process ... I don't know the "signature" of whatever getContentFromAPI is, but, if it follows "standard" node callback "signature" - then your process shouldbe as simple as

getContentFromAPI("banana", function(error, data) {
    if (error) {
        // your error handling goes here
    } else {
        doSomeProcess1();
        doSomeProcess2();
        doSomeProcess3();
        doSomeProcess4();
    }
});