简体   繁体   English

NodeJS 和 MongoDB 中的异步故障

[英]async trouble in NodeJS and MongoDB

i'm trying to create an array which should have an items with open quotation.我正在尝试创建一个数组,该数组应该有一个带有开放引号的项目。 i have an Items DB in Mongo with key "open_quotation", if there is no quotation for this item => open_quotation: null.我在 Mongo 中有一个带有键“open_quotation”的 Items DB,如果该项目没有报价 => open_quotation:null。 i want to map all the array items and to check if there is any open quotations for this item, if there are an open quotation - i want to push it to another array, whihc I created, and to send to client.我想 map 所有数组项目并检查是否有此项目的任何未结报价,如果有未结报价 - 我想将其推送到我创建的另一个阵列,并发送给客户。 the problem that when i do map method on items array it is an async function and i get an array already after that the response has been send... so the client receive it as an empty array.问题是,当我对项目数组执行 map 方法时,它是异步 function 并且在发送响应之后我已经得到了一个数组......所以客户端将它作为一个空数组接收。 pls help to solve this problem.请帮助解决这个问题。

const{items}= req.body;
const quotations=[];
items.map(async item=>{ const i=await Item.findOne({_id: item._id})
if(i){
`if(i.openquotation){ quotations.push(i)}`
return
)}
res.send({response: true, quotations:quotations}) 



`````

Can you try that:你能试试吗:

try {
    const response = await Promise.all(items.map(item => Item.findOne({_id: item._id})));
    const quotations = response.filter((elem) => !!elem.openquotation);
    res.send({ response: true, quotations });
} catch (error) {
    res.send({ response: false, error });
}

you can use async and q module for find query in loop您可以使用asyncq模块在循环中查找查询

when you run mainFunction() , mainFunction calls getData()当你运行mainFunction()时, mainFunction调用getData()

let async = require('async');
let q = require('q');

const mainFunctio = async()=>{
  const{items}= req.body
  console.log("start")
  resultFromFindLoob  = await getData(items)
  console.log("finish");
  console.log(resultFromFindLoob)
}


const getData = async (items)=>{
  let defer =q.defer();
  let result = []
  async.eachSeries(items , async(item)=>{ // like a for
    try {
      let i = await Item.findOne({_id: item._id}).lean();
      //do something for result (processing)
      if(i)
      result.push(i)
    } catch (error) {
      console.log(error)
    }
  },()=>{ //callback when finish loop
    console.log("finish findone() loop")
    defer.resolve(result)//return the result
  })
  return defer.promise
}

mainFunctio()

restult of mainFunction() based on console.log mainFunction() 基于 console.log 的结果

1.start mainFunction
2.start getData
3.finish find loop getData
4.finish mainFunction
5.final result : .....

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

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