如何避免 Node.js 中服务调用链的嵌套 hell ,在某些情况下我想抛出给定的错误并退出整个链?这是链的示例:
- 加载 Mongoose 对象。
- 如果加载失败,
res.send(404)
;如果加载成功,则转到下一个then()
。 - 调用第 3 方 API 来获取一些数据。
- 如果 API 调用失败,请发送正确的响应(为了解决此问题,假设正确的状态代码为
500
) 如果 API 调用成功,则渲染页面。
SomeMongooseModel.findOne({id:123}).exec() .then(function(response) { // If group is empty, would like to res.send(404) and resolve the // promise immediately. }) .then(function(response) { // Hit 3rd party API to retrieve data. If there's an issue, return // response code of 500 and resolve promise immediately. // Assuming the API call was a success, build out an object and render // the page like so: res.render('some.template', {data: some_data}); });
我认为这是我想要实现的目标的一个很好的例子,但是如果我们有更多的异步调用需要处理怎么办?怎样才能立即退出链条呢?我做了一些搜索,我知道我还有很多东西需要学习,但我没有找到立即退出链条的能力。
最佳答案
当面对这个问题时,我通常将所有内容分离到函数中,然后将引用传递到 Promise 中。有了好名字,也有利于阅读:
function resolveNotFoundIfGroupEmptyOrForwardResponse( response ) { res.send(404) }
function hit3rdPartyApiBasedOnResponse( response ) {
// throw exception if there is an issue. next step will run the failure state
}
function render500() { ... }
function renderTemplateWithData( some_data ) {
res.render('some.template', {data: some_data});
}
SomeMongooseModel.findOne({id:123}).exec()
.then( resolveNotFoundIfGroupEmptyOrForwardResponse )
.then( hit3rdPartyApiBasedOnResponse )
.then( renderTemplateWithData, render500 )
.done();
如果函数需要的输入参数不是来自 Promise 链,那么我通常会执行一个返回函数的函数。
function doStuffWithParamsCommingFromTwoSides( main_input ) {
return function( promise_input ) {
...
}
}
then( doStuffWithParamsCommingFromTwoSides( "foobar" ) )
<小时/>
遵循 Promises/A+ 规范,then
步骤如下所示:
promise.then(onFulfilled, onRejected, onProgress)
每当抛出异常时,下一步都会运行onRejected
。最终冒泡到done
,这也可以用来捕获异常冒泡。
promise.done(onFulfilled, onRejected, onProgress)
关于javascript - Node 中的多个 Promise 以及错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24519320/