Javascript Question

Nodejs: Dealing with Multiple Promise callbacks (Callback hell)

I have a 8 callbacks that depends each other. My idea
it's have a more readeable process but I don't undertand how to deal with this.

A 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?

Answer

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.