Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs: Dealing with Multiple Promise callbacks (Callback hell)

I have 8 callbacks that depend on each other. My idea is to have a more readable process but I don't understand how to deal with this.

An example of my callback hell is:

return new Promise(function (resolve, reject) {
 client.command("Command")
  .then(function () {
   client.command(command1)
    .then(function () {
     client.command(command2)
      .then(function () {
       client.command(command3)
        .then(function () {
         client.command(command4)
          .then(function () {
           client.command(command5)
            .then(function () {
             client.command(command6)
              .then(function () {
               client.command(command7)
                .then(function () {
                 client.command(issue)
                  .then(function () {
                   client.command(command8)
                    .then(function (result) {
                     resolve(result.substring(0, 6));
                    });
                  });
                });
              });
            });
          });
        });
      });
    });
  });
});

Anyone knows how to deal with this?

like image 354
Gonzalo Pincheira Arancibia Avatar asked Nov 17 '25 11:11

Gonzalo Pincheira Arancibia


1 Answers

You can flatten this triangle out by returning each promise, for example:

return new Promise(function(resolve, reject) {
    client.command('Command')
        .then(function () {
          return client.command(command1);
        }).then(function() {
          return client.command(command2);
        }).then(function(result) {
          resolve(result.substring(0, 6));
        });
});

EDIT: You can create an array of all your promises and call Promise.each, on the array, as well.

like image 61
Joe Attardi Avatar answered Nov 19 '25 02:11

Joe Attardi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!