gpt4 book ai didi

javascript - 打破 promise 和异步等待的链条

转载 作者:行者123 更新时间:2023-12-02 22:12:35 28 4
gpt4 key购买 nike

我有以下 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);
});
});
};

我在这里称之为:

  // 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。它仍然是一条链,但格式不同。顺便说一句,扔掉步骤 2 和 5。

要使用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()

关于javascript - 打破 promise 和异步等待的链条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513953/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com