3

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?

Kamen Minkov
  • 3,324
  • 1
  • 14
  • 21

3 Answers3

4

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.

Joe Attardi
  • 4,381
  • 3
  • 39
  • 41
0

I assume that client.command returns a promise. Then do:

return client.command("Command")
  .then(function (resultOfCommand) {
    return client.command(command1)
  })
  .then(function (resultOfCommmand1) {
    return client.command(command2)
  })

and so on

You can also use q

const q = require('q')
return q.async(function * () {
  yield client.command('Command')
  yield client.command(command1)
  ...
  return client.command(command8)
})()
Gabriel Furstenheim
  • 2,969
  • 30
  • 27
0

It's called async/await JS

/**
 * If some command reject or throw errors, it'll break and foo rejects
 */
async function foo () {
    var command1 = await client.command("Command")
    await client.command(command1)
    await client.command(command2)
    await client.command(command3)
    await client.command(command4)
    await client.command(command5)
    await client.command(command6)
    await client.command(command7)
    await client.command(issue)
    var result = await client.command(command8)
    return result.substring(0, 6)
}

foo()
    .then(result_substr => console.log(result_substr))
    .catch(e => console.error(e))
Fernando Carvajal
  • 1,869
  • 20
  • 19