复杂的Q承诺:一个承诺创造了一系列其他承诺

时间:2014-08-14 19:14:40

标签: javascript node.js promise

我有一个http请求,应该返回一个任务列表。但是,这些任务是以复杂的方式生成的。这是它的工作原理。

  1. 从数据库中获取所有当前任务
  2. 使旧的任务失效
  3. 从数据库获取用户个人资料
  4. 如果用户没有配置文件且创建配置文件的任务不存在,请添加用于创建配置文件的任务
  5. 此外,如果尚未创建每日任务,则对于用户具有的每个子配置文件,进行日常任务并将其保存到数据库中。
  6. 将所有任务返回给HTTP调用者
  7. 我在这里列出这一切,以防有更好的方法。根据我的理解,我应该承诺DB调用,然后是操作任务/配置文件数据的promises。

    我不明白的是如何将日常任务所需的N个承诺添加到我的承诺链中。我还需要最终进程可用的所有数据来返回新创建的任务列表。我应该以某种方式嵌套承诺吗?

    目前,我认为它是这样的:

    var taskPromise = dbPromise(serverName, taskRequest, params);
    var profilesPromise = dbPromise(serverName, profilesRequest, params);
    
    Q.all([taskPromise, profilesPromise])
    .then(function(arrayOfTasksAndProfiles){
               //do calculations and create an object like {tasks:[], profile:profile, subprofiles:[]})
    .then(function(currentDataObject) {
              var deferred = Q.defer();
              var newTasksToBeCreated = // make a list of all the new tasks I want to create
              var promisesForNewTasks = [] // create an array of promises that save each of the new tasks to the server
              Q.all(promisesForNewTasks)
              .then(function(returnedIDsForNewTasks) {
                       // somehow match the returned IDs to the newTasksToBeCreated and add them on
                       currentDataObject.newTasks = newTasksToBeCreated
                       deferred.resolve(currentDataObject);
                     });)
    .then(function(currentDataObject) {
              // now that the currentDataObject has all the tasks from the DB, plus the new ones with their IDs, I can respond with that information
              res.json(currentDataObject))
    .done();
    

    我必须多次调用DB来创建新任务,并且我需要将那些追加到我从DB收到的其他任务中,并且我能看到的唯一方法是嵌套Q. all()调用。

    “必须有更好的方法。”

1 个答案:

答案 0 :(得分:1)

只有一件事:不要创建需要手动解决的自定义deferred。相反,只需return处理程序中的then;以及return .then()来电的承诺{/ 1}}。

.then(function(currentDataObject) {
    var newTasksToBeCreated = // make a list of all the new tasks I want to create
    var promisesForNewTasks = [] // create an array of promises that save each of the new tasks to the server
    return Q.all(promisesForNewTasks)
//  ^^^^^^
    .then(function(returnedIDsForNewTasks) {
         // somehow match the returned IDs to the newTasksToBeCreated and add them on
         currentDataObject.newTasks = newTasksToBeCreated
         return currentDataObject;
//       ^^^^^^
     });
})

否则,它看起来很好。如果您在将返回的ID与任务匹配时遇到问题 - 请不要这样做。相反,让每个promisesForNewTasks解析为自己的任务对象(与id结合?)。