【发布时间】:2020-01-03 23:10:58
【问题描述】:
我有以下承诺:
var aggregatePromise = () => {
return new Promise((resolve, reject) => {
EightWeekGamePlan.aggregate([
{
$match: {
LeadId: { $in: leads },
Week: week
}
},
{
$group: {
_id: {
LeadId: "$LeadId"
},
total: { $sum: "$TotalClaimsToBeClaimedByClientType" }
}
},
{
$match: {
total: { $lte: 5 - howManyClaims }
}
}
])
.then(leads => {
if (leads !== null) {
resolve(leads);
} else {
reject("Couldn't find any Leads");
}
})
.catch(err => {
reject(err);
});
});
};
我在这里称呼它:
// Step 2
var callAggregatePromise = async () => {
var result = await aggregatePromise();
return result;
};
在这里使用它:
//Step 3: make the call
callAggregatePromise().then(result => {
const winners = result.map(m => ({
LeadId: m._id.LeadId
}));
const flattened = winners
.reduce((c, v) => c.concat(v), [])
.map(o => o.LeadId);
console.log(flattened);
// Step 4 - declare 2ND Promise
var updateLeadsPromise = () => {
return new Promise((resolve, reject) => {
EightWeekGamePlan.updateMany(
{
LeadId: {
$in: flattened
},
TargetedToBeClaimedByClientType: groupTarget,
Week: week
},
{
$inc: {
TotalClaimsToBeClaimedByClientType: howManyClaims
}
}
)
.then(leadsUpdated => {
if (leadsUpdated !== null) {
resolve(leadsUpdated);
} else {
reject("Failed to update requested leads!");
}
})
.catch(err => {
reject(err);
});
});
};
//Step 5 : Call 2ND promise
var callUpdateLeadsPromise = async () => {
var resAgg = await updateLeadsPromise();
return resAgg;
};
//Step 6 : make the call to the "updateLeadsPromise"
callUpdateLeadsPromise().then(result1 => {
console.log(result1);
if (result1.ok === 1) {
// TODO
}
});
});
问题在于步骤4)5)6) 依赖于步骤3) 的结果。
我怎样才能打破链条并使它们独立?
【问题讨论】:
-
不确定您到底想要做什么,但对于独立操作,您通常会创建单独的 Promise 并使用
Promise.all()或Promise.allSettled()跟踪它们,具体取决于您想要的拒绝行为。 -
只是不要使用 await,启动两个不同的 Promise
-
@jfriend00,我猜 Promise.all 在你想在一个地方执行 Promise 结果时使用,因为它允许将所有结果一起运行该函数......如果你不需要它 - 你可以只需开始两个不同的承诺,就是这样
-
@DmitryReutov - 是的。
Promise.all()或Promise.allSettled()将在某些代码想知道什么时候完成时使用。如果不是这种情况,那么只需启动多个单独的 Promise 并在各自的链中单独处理它们。我不清楚 OP 的问题是什么。
标签: javascript node.js promise es6-promise