简体   繁体   English

Nodejs在没有等待的情况下调用异步function有什么问题吗?

[英]Nodejs any problem in calling async function without await?

I have an endpoint where I want to do some async post processing in which user is not interested in, so I want to process them asynchronously and send send the response the user.我有一个端点,我想做一些用户不感兴趣的async后处理,所以我想异步处理它们并向用户发送响应。

something like this.像这样的东西。

const createOrder = async (req,res)=>{

  const order = await doCreateOrder(); //creates the order
  somePostProcessing().catch(()=>{
       //handle errors
    });//asycn function which does some db/network operations(not interested in results)
  return reply.send(order)

}

But I have a concern that would it cause any issues like memory leak(my team lead says so) and so on?但我担心它会导致任何问题,例如 memory 泄漏(我的团队负责人这么说)等等? also what is the best way or other options to do such post processing in nodeJS?在nodeJS中进行此类后期处理的最佳方式或其他选择是什么?

It is not a problem to ignore the result of a promise.忽略 promise 的结果不是问题。 It's totally optional whether you listen for the successful completion of a promise or not.您是否聆听 promise 的成功完成完全是可选的。 There are sometimes reasons to not care.有时有理由不在乎。 For example, I often don't make a function wait for the closing of a file at the end of the function.例如,我经常不让 function 等待 function 末尾的文件关闭。

It is a problem to ignore a rejected promise as that's analogous to an unhandled exception in synchronous code.忽略被拒绝的 promise 是一个问题,因为这类似于同步代码中的未处理异常。

So, as long as you are handling all possible errors which it looks like you are with somePostProcessing().catch(...) , then it's no problem to ignore the completion.因此,只要您正在处理所有可能的错误,就像您使用somePostProcessing().catch(...)一样,那么忽略完成就没有问题。

Note: you do need to make sure your code is anticipating what happens if there's an error in await doCreateOrder() as that will immediately reject the promise returned by createOrder() so the caller of createOrder() needs to have a handler for that rejected promise OR you need a try/catch inside this function to catch and handle that possible error.注意:您确实需要确保您的代码预测到如果await doCreateOrder()中出现错误会发生什么,因为这将立即拒绝 createOrder() 返回的 promise 因此 createOrder createOrder() createOrder()的调用者需要有一个处理程序来处理被拒绝的promise 或者您需要在此 function 中使用try/catch来捕获和处理可能的错误。

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

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