0

I have some code that is kinda working (the functions do what they are supposed to do), but it looks ugly and I am sure there is a better way to do this.

I need to run three functions, one after the other, if they are successful. What I have done looks like this.

Is this correct? Is there a better (I am sure) way to do this?

 function1({
        dosomething
    }, function(err, result) {
        if (err) {
            callback('There was an error: ' + err);
        }
        else{
            console.log(' function 1 done');
            function2({
                somethingelse
            }, function(err, result) {
                 if (err) {
                    callback('There was an error on function2: ' + err);
                }
            else{
                console.log('function2 ok');
                function3({
                    blah
                    function(err, result) {
                       console.log(result);
                       console.log(err);
                       callback(err, response)
                });
            }
        });
    }
    
  }
);
jsabina
  • 188
  • 14
  • 2
    Welcome to [callback hell](http://callbackhell.com/). My suggestion is to [promisify](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) these and then you can use the promise API or `async`/`await` to handle this without going mad. – VLAZ Jun 23 '20 at 18:53
  • 1
    What are your three functions doing that require them to continue with callbacks? API requests? Filesystem operations? This info will inform the exact approach you should take here. – Klaycon Jun 23 '20 at 18:54
  • API requests exactly – jsabina Jun 23 '20 at 20:00
  • thanks a lot for your comments.. I went to read both resources and they are all interesting. I will start playing a bit with the code and see which is the best approach – jsabina Jun 23 '20 at 20:42

0 Answers0