简体   繁体   English

没有回调的Node.js异步功能会阻塞主线程?

[英]Node.js async function without callback blocks main thread?

So I noticed after making some recent changes to my Node.js app, the server stops responding after some requests. 因此,我注意到对Node.js应用程序进行了最近的更改后,服务器在某些请求后停止响应。 I think I've nailed down the culprit but want to confirm. 我想我已经确定了罪魁祸首,但想确认一下。

So I have a function which removes a file from the filesystem after use, I don't really care about the response from the file deletion so I just ignore it. 因此,我有一个使用后从文件系统中删除文件的功能,我不太在意文件删除的响应,因此我将其忽略。

So lets say I have this function: 所以可以说我有这个功能:

removeFileAtPath(filePath, callback) {
  fs.unlink(filePath, (err) => {
    if (callback) {
      return callback(err)
    }
  });
}

This gets called from a middleware function, so normally would be called like this: 这是从中间件函数调用的,因此通常这样调用:

uploadFile(req, res, next) {
  // Do something
  removeFileAtPath(path, (error) => {
     if (error) { /* handle error */ }
     res.send(someResponse)
  });
}

But since I don't care about the function response, I call the removeFileAtPath function like this: 但是由于我不在乎函数响应,所以我这样调用removeFileAtPath函数:

uploadFile(req, res, next) {
  // Do something
  removeFileAtPath(path);    // No callback passed in here
  res.send(someResponse);
}

Will something like this block the main loop or is my issue likely somewhere else? 这样的事情会阻塞主循环吗?还是我的问题可能在其他地方?

尝试在中间件结尾处调用next()函数

No, it doesn't block - if you mean the main thread and the event loop - fs.unlinkSync would block in that sense. 不,它不会阻塞-如果您是指主线程和事件循环fs.unlinkSync将在这种意义上阻塞。

But you still need to make sure that you return the response or call the next middleware - otherwise you will "block" the request from being served even though the thread and event loop will not be blocked in the usual sense and your server will still be able to handle other requests and events. 但是,您仍然需要确保返回响应调用下一个中间件-否则,即使通常情况下不会阻塞线程和事件循环,并且您的服务器仍会处于“阻塞”状态,您仍将“阻塞”请求的服务能够处理其他请求和事件。

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

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