首页 > 解决方案 > 在节点 Js 中突破/绕过承诺链

问题描述

我是 nodeJs 的新手,正在尝试开发一种功能。根据这个,我需要获取一个可以以不同形式出现在 4 个地方之一的数据,并且我需要从我首先找到它的地方返回一个映射对象。所以让我们考虑一个例子,我试图在动物园里寻找一种食肉动物(老虎、狮子、豹),并且有不同的处理程序来找到它们中的每一个。每当我找到动物时,我需要将它包裹在 CarnivorousWrapper 中并将其归还并跳过梯子下面的所有内容(因此,如果首先找到老虎,则不要找到任何其他动物)。一种实现方法是通过如下所示的回调地狱

function getCarnivorous () {
  return getTiger()
    .then(tigerResponse => {
      if (tigerResponse) {
        return carnivorousAdapter(tigerResponse);
      } else {
        return getLion()
          .then(lionResponse => {
            if (lionResponse) {
              return carnivorousAdapter(lionResponse);
            } else {
              return getLeopard()
                .then(lionResponse => {
                  if (lionResponse) {
                    return carnivorousAdapter(lionResponse);
                  } else {
                    throw NotFoundException('Animal not found');
                  }
                });
            }
          });
      }
    });
}

我需要了解这是否可以以更好的方式完成,例如 Promise ladder,以及如何在找到老虎后立即退出。

标签: node.jspromise

解决方案


您现在可以使用 es6 async/await 功能 ( https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/async_function ) 来获得更具可读性的代码:

async function getCarnivorous () {
  let response = await getTiger()
  if(!response) {
    response = await getLion()
  }
  if(!response) {
    response = await getLeopard()
  }
  if(!response) {
    throw NotFoundException('Animal not found')
  }
  return carnivorousAdapter(response)
}
    

推荐阅读