2016-10-24 6 views
3

서로 의존하는 8 개의 콜백이 있습니다. 내 아이디어 은 더 읽기 쉬운 프로세스를 가지고 있지만이 문제를 어떻게 처리해야하는지 이해할 수 없습니다.Nodejs : 여러 약속 콜백 다루기 (콜백 지옥)

내 콜백 지옥의 예는 다음과 같습니다

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)); 
        }); 
        }); 
       }); 
       }); 
      }); 
      }); 
     }); 
     }); 
    }); 
    }); 
}); 

사람이 처리하는 방법을 알고?

+0

의 가능한 속는 https://stackoverflow.com/questions/22539815/arent-promises-just-callbacks – JohnnyHK

답변

5

당신은 예를 들어, 각 약속을 반환하여이 삼각형을 평평하게 할 수 있습니다

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)); 
     }); 
}); 

편집 : 당신은 모든 약속의 배열을 만들뿐만 아니라, 배열에 Promise.each를 호출 할 수 있습니다.

+1

이것은 나에게 많은 의미가 있습니다. 감사! –

1

나는 client.command가 약속 한 것을 반환한다고 가정합니다. 그런 다음을 수행하십시오

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

에 당신은 또한 사용할 수 있습니다 Q

const q = require('q') 
return q.async(function *() { 
    yield client.command('Command') 
    yield client.command(command1) 
    ... 
    return client.command(command8) 
})()