[英]Multiple promises in Node with error handling
How can I avoid nesting-hell with a chain of service calls in Node.js, where I'd like to throw a given error and exit the entire chain in certain instances? 我如何避免在Node.js中发生服务调用链嵌套的问题,在这种情况下我想抛出给定的错误并在某些情况下退出整个链? Here's an example of the chain:
这是链的示例:
res.send(404)
; res.send(404)
; if load succeeds, go to the next then()
. then()
。 500
just for the sake of this problem) 500
) If API call succeeds, render the page. 如果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}); });
I think this is a decent example of what I'm trying to achieve, but what if we had even more async calls to handle? 我认为这是我要实现的目标的一个很好的例子,但是如果我们要处理更多的异步调用怎么办? How can we exit the chain immediately?
我们如何才能立即退出连锁? I've done a bit of searching and I know that I have a lot more to learn, but I'm not finding the ability to simply exit the chains immediately.
我做了一些搜索,我知道我还有很多东西要学习,但是我没有找到立即退出链的能力。
When faced with this I normally separate everything into functions, which I then pass a reference into the promise. 遇到这种情况时,我通常将所有内容分离为功能,然后将其传递给Promise。 With good names it also benefits the reading:
有了好名字,它也有利于阅读:
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();
If the function requires an input param that is not comming from the promise chain, then I normally do a function that returns a function. 如果函数需要的输入参数不是来自Promise链的,那么我通常会做一个返回函数的函数。
function doStuffWithParamsCommingFromTwoSides( main_input ) {
return function( promise_input ) {
...
}
}
then( doStuffWithParamsCommingFromTwoSides( "foobar" ) )
Following Promises/A+ specification, the then
steps look like this: 按照Promises / A +规范,
then
步骤如下所示:
promise.then(onFulfilled, onRejected, onProgress)
Whenever an exception is thrown the next step will run the onRejected
. 每当抛出异常时,下一步将运行
onRejected
。 Eventually bubbling up to the done
which can also be used to catch the exception bubble. 最终冒泡直到
done
,也可以用来捕捉异常气泡。
promise.done(onFulfilled, onRejected, onProgress)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.