Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

javascript - 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. 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. 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. 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}) 



`````
question from:https://stackoverflow.com/questions/65887545/async-trouble-in-nodejs-and-mongodb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...