async / await阻塞事件循环吗? [英] Does async/await blocks event loop?
问题描述
我正在阅读不要阻止事件循环来自Node.js指南。有一句话说:
I was reading Don't Block the Event Loop from the Node.js guide. There was a line saying:
你应该确保你永远不会阻止事件循环。换句话说,每个JavaScript回调都应该快速完成
。这个
课程也适用于你的await
,你的Promise.then
,等等on。
我开始怀疑,如果,某些API调用数据库,我等待
ing需要一些时间才能解决,这是否意味着我用 await
调用阻止了事件循环?
I started to wonder, what if, some API call to the database which I'm await
ing is taking some time to resolve, does that mean that I have blocked the event loop with that await
call?
之后,我开始测试一些自编代码,但经过测试后我仍然不清楚如何阻止 await
工作。以下是一些测试代码:
After that, I started testing some self written codes but after testing I'm still not clear how blocking through await
works. Here are some testing codes:
假设我正在使用express进行测试。我理解为什么对 / test
路由进行2次API调用会阻止事件循环。
Assuming, that I'm using express for testing. I understand why making 2 API calls to the /test
route blocks the event loop in this case.
function someHeavyWork() {
// like calling pbkdf2 function
}
app.get('/test', (req, res) => {
someHeavyWork();
res.json(data);
});
但在这种情况下不会发生这种情况。
But that doesn't happen in this case.
function fakeDBCall() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(data);
}, 5000)
})
}
app.get('/test', async (req, res) => {
const data = await fakeDbCall();
res.json(data);
})
这可能是因为我在 async / await
的情况下对阻塞的工作方式缺乏了解。
This may be because of my lack of understanding of how blocking works in the case of async/await
.
推荐答案
与看起来相反,等待
不会阻止。它只是承诺的 语法糖 。什么都没有阻止;它可能看起来阻塞以允许代码同步,但这只是承诺的糖。例如,这可能看起来是同步的:
Contrary to what it seems, await
does not block. It's just syntactic sugar over promises. Nothing is blocked; it may look blocking to allow code to be synchronous, but that's just sugar over promises. For example, this may look synchronous:
const response = await fetch(…);
const json = await response.json();
const foo = JSON.parse(json); // Using json here, even though my request was async!
但事实并非如此。一旦你去了它,所有你得到的是非阻塞的承诺:
But it's not. Once you desugar it, all you get are promises, which are nonblocking:
fetch(…)
.then(response => response.json())
.then(json => {
const foo = JSON.parse(json);
});
如果等待
,那绝对是灾难性的阻塞。 JavaScript运行时通常是单线程。这意味着只要您发出请求或其他异步操作(例如使用文件系统),用户交互和其他进程就会停止。在相关的说明中,这与动态导入一起是针对顶级<$ c的主要论点。 $ c>等待
It would be absolutely catastrophic if await
were blocking. JavaScript runtimes are generally single threaded. That means user interaction and other processes would cease whenever you made a request or some other async operation such as using the filesystem. On a related note, this is, along with dynamic imports, are the main argument against top level await
这篇关于async / await阻塞事件循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!