我有一个http请求,应该返回一个任务列表。但是,这些任务是以复杂的方式生成的。这是它的工作原理。
我在这里列出这一切,以防有更好的方法。根据我的理解,我应该承诺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()调用。
“必须有更好的方法。”
答案 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结合?)。