gpt4 book ai didi

javascript - node.js 中的回调是始终异步还是始终同步?或者它们可以是 "sometimes one, sometimes the other"吗?

转载 作者:搜寻专家 更新时间:2023-10-31 23:42:08 27 4
gpt4 key购买 nike

我正在尝试用 node.js 制作一些东西,我(和其他开始学习 node 的人一样)对它的异步性质有疑问。我四处搜索了一下,但找不到关于它的具体问题的答案(也许我只是搜索得不是很好......),所以这里是:

一般情况下,node.js 回调是否保证是异步的(如果文档这么说)?如果你自己制作接受回调的函数,你应该以这样的方式设计,使它们始终异步还是始终同步?或者它们可以有时同步,有时不同步?

例如,假设您想通过 Internet 加载一些数据,并且您创建了一个函数来加载它。但数据不会经常更改,因此您决定将其缓存起来以备将来调用。您可以想象有人会像这样编写该函数:

function getData(callback) {
if(dataIsCached) {
callback(cachedData)
} else {
fetchDataFromNetwork(function (fetchedData) {
dataIsCached = true;
cachedData = fetchedData;
callback(fetchedData);
});
}
}

其中 fetchDataFromNetwork 是一个异步执行其回调的函数(这有点伪代码,但我希望你明白我的意思)。

如果数据没有被缓存,这个函数只会异步触发,如果它被缓存,它只会直接执行回调。在那种情况下,函数的异步特性毕竟是完全没有必要的。

这种事情是不是气馁了?该函数的第二行是否应该改为 setTimeout(function () {callback(cachedData)}), 0) 以保证它异步触发?

我问的原因是我前一段时间看到一些代码,其中回调内的代码简单地假设回调外的函数的其余部分在回调内的代码之前执行。我对此有点退缩,心想“但是你怎么知道回调将异步触发?如果它不需要并同步执行怎么办?为什么你会假设每个回调都是有保证的异步?”

如能对这一点作出任何澄清,我们将不胜感激。谢谢!

最佳答案

你的假设都是正确的。

Are node.js callbacks, in general, guaranteed to be asynchronous if the documentation says so?

是的。当然还有functions with async callbacks and functions with sync callbacks , 但两者都没有。

If you make your own functions that take callbacks, should you design in such a way so that they're either always asynchronous or always synchronous?

是的。

They could be sometimes synchronous, sometimes not, such as a cache? Is this kind of thing discouraged?

是的。 Very much d̲̭i̫̰̤̠͎͝ͅͅs͙̙̠c̙͖̗̜o͇̮̗̘͈̫ų̗͔̯ŕa҉̗͉͚͈͈̜g͕̳̱̗e҉̟̟̪͖̠̞ͅd͙͈͉̤̞̞̩ .

Should the second line of the function be setTimeout(function () {callback(cachedData)}), 0) instead, to guarantee that it fires asynchronously?

是的,这是个好主意,但在 Node 中您更愿意使用 setImmediate or process.nextTick而不是 setTimeout
或者使用 promises,它确实保证了异步性,这样您就不必担心自己会延迟事情。

I saw some code a while back where the code inside the callback simply assumed that the rest of the function outside the callback had executed before the code inside the callback. I recoiled a little at that

是的,可以理解。即使您使用的 API 保证异步,编写代码仍然会更好,以便它可以按执行顺序读取。如果可能,您应该将执行的事情放在异步回调之前(异常证明规则)。

关于javascript - node.js 中的回调是始终异步还是始终同步?或者它们可以是 "sometimes one, sometimes the other"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31944806/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com