简体   繁体   English

如何解决我的代码中的异步问题?

[英]How can I solve the asynchronous problem in my code?

Even though the updating is happening successfully in the DB ( collection().... ) - the batchIdsAdded data that's supposed to be pushed into packIdsOwned and packsOwnedMetadata arrays in the for loop is displaying as null in the response.即使更新在数据库中成功发生( collection().... ) - 应该在for循环中推入packIdsOwnedpacksOwnedMetadata数组的batchIdsAdded数据在响应中显示为null

I know there's an asynchronous problem in my code but I'm not sure how to tackle it in my code even after taking a look at this popular SO post revolving around this and trying out some of the suggestions there.我知道我的代码中存在异步问题,但我不确定如何在我的代码中解决它,即使在查看了围绕此问题的流行SO 帖子并尝试了其中的一些建议之后也是如此。 Unfortunately, I've hit a wall and I'm very stuck.不幸的是,我碰壁了,我很困。

How can I make it so that all the batchIdsAdded data is pushed to the arrays correctly?如何才能使所有batchIdsAdded数据正确推送到数组?

let packsOwned = result.packsOwned;
let packIdsOwned = [];
let packsOwnedMetadata = [];

let batchIdsAdded = {};

result.packsOwned.push(...batchPackIdInput.map(item => (batchIdsAdded = {"PackId" : item}, collection.updateOne(query, {$push: {"packsOwned" : { $each: [batchIdsAdded]}}}, result['userName']))));  

// Data to be displayed in the response
for(let i = 0; i < packsOwned.length; i++) {
   packIdsOwned.push(packsOwned[i].PackId);
   packsOwnedMetadata.push({
      PackID : packsOwned[i].PackId
   });
}

I'm not seeing where the async is happening, my best guess is collection.updateOne.我没有看到异步发生在哪里,我最好的猜测是 collection.updateOne。 If that's the case, then you'll need to Promise.all() the map since at the time of calling it's still a bunch of promises.如果是这种情况,那么您需要 Promise.all() 地图,因为在调用它时它仍然是一堆承诺。 Unless result is also in an async context tho, it won't matter since everything will be off the stack by the time it goes to push.除非结果也在异步上下文中,否则这无关紧要,因为在推送时所有内容都将脱离堆栈。 You'll need to keep everything in an async context after you start one.启动后,您需要将所有内容保持在异步上下文中。

 async function updateResult() { let batchIdsAdded = {}; return await result.packsOwned.push(Promise.all(...batchPackIdInput.map( item => ( batchIdsAdded = {"PackId" : item}, collection.updateOne( query, {$push: {"packsOwned" : { $each: [batchIdsAdded]}}}, result['userName'] ) ) ) )); } async function display() { let packsOwned = await updateResult().packsOwned; let packIdsOwned = []; let packsOwnedMetadata = []; return packsOwned.forEach(({PackId}) => { packIdsOwned.push(PackId) packsOwnedMetadata.push({PackID: PackId}) }) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM