[英]Q Promises: how to sequentially try multiple registries
I could need some help with Q promises for a node.js application. 对于node.js应用程序的Q promise,我可能需要一些帮助。 My use case is as follows:
我的用例如下:
What I'm struggling with is to create/return a promise that finishes, when the information has been found. 我正在努力的是在找到信息后创建/返回完成的承诺。
Something like (pseudo code): 类似于(伪代码)的东西:
var deferred = Q.defer(id)
foreach repo in repositories {
var p = repo.findById(id)
.then deferred.resolve(order)
p.waitForThePromiseToFinish
if (p.success) break
}
An idea how to implement this? 一个想法如何实现这一点? Any help is appreciated.
任何帮助表示赞赏。
Pretty much like your pseudocode except we use thenable chaining since the actions are async: 与我们的伪代码非常相似,不同之处在于我们使用可链接的链接,因为操作是异步的:
var p = Promise.resolve(); // start empty promise;
repositories.forEach(function(repo){
p = p.then(function(result){ // chain
if(result.success) return result; // assumes that result.success is true if good
return repo.findById(id); // call find by Id
});
});
This will resolve to a promise p
that will be the first repository to be successfull, or a rejection if all failed - note that this assumes your findById
API is such that it returns a value with result.success === true
on a successful find and result.success === false
otherwise. 这将解析为将成为第一个成功存储库的promise
p
,或者如果所有失败都将被拒绝-请注意,这假设您的findById
API如此,则它将返回带有result.success === true
的值。和result.success === false
否则为result.success === false
。 Let me know if you have issues adapting this to your actual API or if you have issues. 如果您在将其调整为实际的API时遇到问题,或者遇到问题,请告诉我。 Have fun :)
玩得开心 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.