Javascript 复杂Q承诺:一个承诺创建一系列其他承诺
我有一个http请求,它应该返回一个任务列表。但是,这些任务是以复杂的方式生成的。这就是它的工作原理Javascript 复杂Q承诺:一个承诺创建一系列其他承诺,javascript,node.js,promise,Javascript,Node.js,Promise,我有一个http请求,它应该返回一个任务列表。但是,这些任务是以复杂的方式生成的。这就是它的工作原理 从数据库获取所有当前任务 使旧任务过期 从数据库中获取用户配置文件 如果用户没有配置文件,并且创建配置文件的任务不存在,请添加创建配置文件的任务 此外,对于用户拥有的每个子文件,如果尚未创建每日任务,则创建每日任务并将其保存到数据库中 将所有任务返回给HTTP调用方 我把这些都列在这里,以防有更好的方法。据我所知,我应该对这两个DB调用都有承诺,然后再加上操纵任务/概要文件数据的承诺 我不明白的
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()调用
“一定有更好的方法。”只有一件事:不要创建需要手动解决的自定义
延迟。相反,只需从处理程序返回,然后返回;和返回调用的结果承诺
.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与任务匹配时遇到问题,请不要这样做。相反,让每个promisesfornewtask
使用自己的任务对象(与id结合?)进行解析。不要将“任务”与“承诺”混淆。我们能谈谈“待办事项”吗?通常,承诺代表执行任务的结果:-)你是对的,我可能应该将其改为其他内容以避免混淆。当我提到“任务”时,我只是在我的任务类型应用程序中引用一个对象。它们就像:{type:“task”,item:“go to the store”}或{type:“task”,item:“add a user profile”},而不是承诺执行的任务。我认为只要你明确不运行“tasks”就可以了