node.js - 在节点 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,以及如何在找到老虎后立即退出。
解决方案
您现在可以使用 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)
}
推荐阅读
- git - 如何通过 API 获取 Azure DevOps 存储库创建日期
- dataweave - 是否可以在依赖于动态数据的条件下使用 Dataweave 掩码或更新函数?
- javascript - 电子 webview 上传文件错误 net::ERR_ACCESS_DENIED
- ios - Swift - TableView 断言错误:cellForRowAtIndexPath 因为:canEditRowAt()
- r - magrittr 管道函数删除列
- java - 在 Java 的 MongoDB 驱动程序中,如何更新文档列表中的文档?
- javascript - 使用 JavaScript 更改 React 页面内容
- kubernetes - 将流量从 pod 转发到在 localhost 上运行的服务
- go - 调用 Updates() 时 GORM 更新空字段?
- shopify - 液体错误:超过集合的唯一句柄的最大数量。(购物)