简体   繁体   English

异步/等待节点js mongodb中的处理错误

[英]async / await handling error in node js mongodb

I'm using async function in my node, here I'm calling multiple queries with mongodb 我在节点中使用异步函数,在这里我用mongodb调用多个查询

(ie) : (即):

let data1;
let data2;
try{
       data1 = await mongoQuery1
  }catch {
       res.send(error)
  }
try{
      data2 = await mongoQuery2 
  }catch {
       res.send(error)
  }
  res.send({ data1, data2 });

I've confused with this flow. 我对此流程感到困惑。 So, basically All I want to send to user is both data1 and data2 but what happens if the query1 fails because, it will be obviously falls in the first catch block and send response to the user, and then continue executing the next try block, and send the response again, which is totally wrong. 因此,基本上我想发送给用户的都是data1data2但是如果query1失败会发生什么,因为它显然会落在第一个catch块中并向用户发送响应,然后继续执行下一个try块,然后再次发送响应,这是完全错误的。 How can I achieve this, what I want is if any error occured in any catch I want to send the error response back to the user 我要如何做到这一点,我想要的是,如果我想将错误响应发送回用户的任何捕获中发生任何错误,

If all the try block succeeds then only I want to send back the success response to the user, How can I achieve this? 如果所有try块均成功,则仅我想将成功响应发送回用户,我该如何实现?

It's not really clear what you are trying to do. 目前尚不清楚您要做什么。

If you want to stop and just send the error then you can return after calling res.send to stop the function continuing. 如果要停止并仅发送错误,则可以在调用res.sendreturn以停止该函数。

If you want to send the error with the rest of the data then don't call res.send immediately, store the error in data1 and then send it at the end as normal. 如果要与其余数据一起发送错误,不要立即调用res.send ,将错误存储在data1 ,然后res.send在最后发送。

Advice to use Promise.all for your scenario: Both query will be run simultaneously and if there is an error it will immediately throw and got to the catch block. 在您的情况下使用Promise.all建议:这两个查询将同时运行,如果有错误,它将立即抛出并到达catch块。

try {
    const [data1, data2] = await Promise.all([mongoQuery1, mongoQuery2]);
    res.send({ data1, data2 })
} catch {
    res.send(error)
}

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

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