简体   繁体   English

Q的承诺:如何顺序尝试多个注册表

[英]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: 我的用例如下:

  • we need to find (by ID) some information (say an order) 我们需要(通过ID)查找一些信息(例如订单)
  • we have multiple repositories which may contain the information (directory, database, nosql, REST service ...) 我们有多个存储库,其中可能包含信息(目录,数据库,nosql,REST服务...)
  • We have a search sequence. 我们有一个搜索序列。 That is we do not want to search them all in parallel and the fastest wins, but we need to search sequentially one repository after the other 那就是我们不想同时搜索它们并以最快的速度获胜,但是我们需要依次搜索一个存储库
  • We can stop searching and ignore the remaining repositories once we found the information 找到信息后,我们可以停止搜索并忽略其余存储库
  • we already have promises for each repository 我们已经对每个存储库都有了承诺

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.

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