irom
irom

Reputation: 3606

simplifying nested callbacks

I have below code to get result from func1 using callback1. But func1 is using func2 with callback2 and then depends on that second callback either returns result or using func3 with callback3 to get result. Not sure where to put another callback to get one result.

module1.func1(arg1, function (callback1) {
    module1.func2(arg2, function (callback2) {
        if (result2) result = result2;
        else
        module2.func3 (arg3, function (callback3) {
            result = result3;
        })
    })
});

If I add another callback to func3 it will work only in case I don't get result from func2 immediately. Maybe that's all I need , pattern looks too complex for me

module.exports = function (callback) {
    module1.func1(arg1, function (callback1) {
        module1.func2(arg2, function (callback2) {
            if (result2) result = result2;
            else
                module2.func3 (arg3, function (callback3) {
                    result = result3;
                    callback(result) //???
                })
        })
    });
};

Upvotes: 0

Views: 43

Answers (1)

Gunther Rotsch
Gunther Rotsch

Reputation: 155

The nested callback hell can in be tackled in recent JavaScript versions by promisses. One of many resources on the net is

https://github.com/mattdesl/promise-cookbook

Promisses are available in ES6, but also several libraries. I hope this gives you an idea what to look for.

Upvotes: 2

Related Questions