[英]Break a chain in promises and async await
I have the following promise :我有以下承诺:
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);
});
});
};
I call it here :我在这里称它:
// Step 2
var callAggregatePromise = async () => {
var result = await aggregatePromise();
return result;
};
And use it here :并在这里使用它:
//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
}
});
});
The problem is that Step 4)5)6)
are dependent on the result of step 3)
.问题是步骤
4)5)6)
依赖于步骤3)
的结果。
How can I break the chain and make them independent ?我怎样才能打破链条并使它们独立?
To break a chain you will have to await the Promises in order.要打破链条,您必须按顺序等待 Promise。 It will still be a chain but in a different format.
它仍然是一个链,但格式不同。 Btw throw away step 2 and 5.
顺便说一句,扔掉第 2 步和第 5 步。
To use await you have to have it inside a async function.要使用 await 你必须把它放在一个异步函数中。
async function doLeadStuff() {
// awaiting main Promise
const result = await aggregatePromise();
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);
// awaiting updates
const leadsUpdated = await EightWeekGamePlan.updateMany(
{
LeadId: {
$in: flattened
},
TargetedToBeClaimedByClientType: groupTarget,
Week: week
},
{
$inc: {
TotalClaimsToBeClaimedByClientType: howManyClaims
}
}
)
if (leadsUpdated === null) {
throw new Error("Failed to update requested leads!");
}
console.log(result1);
if (result1.ok === 1) {
// TODO
}
}
// calling async function
doLeadStuff()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.