简体   繁体   English

有条件的诺言链

[英]Conditional chaining of promises

I want to chain my promises depending upon if the previous call was resolved or rejected. 我想兑现我的诺言,取决于上一个呼叫是否已解决或拒绝。 I am making a call to server in all promises. 我在所有承诺中都致电服务器。 So, I am writing it like- 所以,我写它像

apiServices.patientsSearch(id)
.then(function(data){
    return callback(null,data);
},function(err){
    return apiServices.studiesSearch(id);
}).then(function(data){
    return callback(null,data);
},function(){
    return apiServices.seriesSearch(id); 
}).then(function(data){
    return callback(null,data);
})
.catch(function(err){
    return callback(false,err);
});

As every then returns a promise object, problem is that catch is always being called if any promise except the last one calls resolve. 当每个返回一个promise对象时,问题在于,如果除最后一个调用之外的任何promise都被解析,则总是调用catch。 One way I am thinking is to check if err is empty and ignore it. 我在想的一种方法是检查err是否为空并忽略它。 Is it the right way to do it ? 这是正确的方法吗?

I am using request module, if I set forever: true, I start getting- 我正在使用请求模块,如果我将其设置为永远:是的,我开始得到-

{ [Error: socket hang up] code: 'ECONNRESET' }

With forever false, it works. 如果永远是错误的,它将起作用。 Why my socket is still busy even after the request has ended ? 为什么即使请求结束后我的套接字仍然很忙? As the next request will go only when reject is called, so socket should be free by that time. 由于下一个请求仅在调用reject时才会执行,因此套接字应该在那个时候可用。

You should only call the callback once. 您只应调用一次callback Don't pass it as the onfulfilled-handler after each promise, call it once in the end: 每次承诺后不要将其作为onfulfilled-handler传递,最后将其调用一次:

apiServices.patientsSearch(id).then(null, function(err){
    return apiServices.studiesSearch(id);
}).then(null, function(){
    return apiServices.seriesSearch(id); 
}).then(function(data){
    callback(null,data);
}, function(err){
    callback(false,err);
});

or 要么

apiServices.patientsSearch(id).catch(function(err){
    return apiServices.studiesSearch(id);
}).catch(function(){
    return apiServices.seriesSearch(id); 
}).then(function(data){
    callback(null,data);
}, function(err){
    callback(false,err);
});

Of course, you shouldn't be calling any callbacks at all in promise-based code, so use this only if you have to interface with legacy code. 当然,您根本不应该在基于Promise的代码中调用任何回调,因此仅在必须与遗留代码接口时才使用此回调。 Otherwise, don't take a callback parameter and just return the promise: 否则,请勿使用callback参数,而仅return诺言:

return apiServices.patientsSearch(id).catch(function(err){
    return apiServices.studiesSearch(id);
}).catch(function(){
    return apiServices.seriesSearch(id); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM