Nodejs:处理多个Promise回调(Callback hell)

时间:2016-10-24 17:36:46

标签: javascript node.js promise

我有8个相互依赖的回调。我的想法 是有一个更可读的过程,但我不明白如何处理这个。

我的回调地狱的一个例子是:

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

任何人都知道如何处理这个问题?

3 个答案:

答案 0 :(得分:4)

您可以通过返回每个承诺来展平这个三角形,例如:

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 :(得分:0)

我假设client.command返回一个promise。然后做:

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

答案 2 :(得分:0)

它叫做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))