如何使这个 JS 函数异步?
function takesTime(){
for (var i = 0; i<some_very_large_number; i++){
//do something synchronous
}
console.log('a');
}
takesTime();
console.log('b');
这打印: 一个 乙 你会如何让它打印: 乙 一个
function takesTime(){
for (var i = 0; i<some_very_large_number; i++){
//do something synchronous
}
console.log('a');
}
takesTime();
console.log('b');
This prints:
a
b
How would you make it print:
b
a
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
另请参阅 setZeroTimeout 以在每个循环中获得几毫秒的时间,尽管人们在那里所做的工作似乎是基于浏览器的。
Also see setZeroTimeout to gain a few milliseconds each loop, although the work people are doing there seems to be browser-based.
我看到它被标记为node.js,所以我将从这个角度回答它:你不应该。通常,如果您阻止,它将是:网络绑定(您应该使用和/或重用 网络库围绕异步方法),I/O 限制(您应该使用和/或重用 I/O 库),或受 CPU 限制。您还没有提供任何关于长时间运行的任务的上下文,并且考虑到您有一个包含
some_very_large_number
的循环不变量,我假设您正在想象一些 CPU 密集型任务迭代大领域。如果您确实受 CPU 限制,则应该重新考虑您的策略。 Node 只存在于一个核心上,因此即使您能够使用多线程,您实际上也只是在白费力气,因为每个请求仍然需要一定量的 CPU 时间。如果您确实打算做一些计算密集型的事情,您可能需要考虑使用排队系统,并使用其他更适合处理数据的方法来处理数据。
I see this is tagged node.js, so I'll answer it from that perspective: you shouldn't. Usually, if you're blocking, it will be: network-bound (you should be using and/or reusing network libraries around asynchronous methods), I/O-bound (you should be using and/or reusing I/O libraries), or CPU-bound. You haven't provided any context for what the long-running task is, and given that you have a loop invariant containing
some_very_large_number
, I'm assuming you're imagining some CPU-intensive task iterating over a large field.If you're actually CPU-bound, you should rethink your strategy. Node only lives on one core, so even if you were able to use multithreading, you'd really just be spinning your wheels, as each request would still require a certain amount of CPU time. If you actually intend on doing something computationally-intensive, you may want to look into using a queuing system, and having something else processing the data that's better designed for crunching it.
Javascript 是基于事件的,一切都发生在单个线程中。使其成为“异步”的方法是使用超时(setTimeout())。
Javascript is event-based, and everything happens in a single thread. The way for you to make it "asynchronous" is to use a timeout (setTimeout()).
您可以使用 Web Worker 来实现您的目标,但您需要一个单独的 js 文件,并且必须添加管道代码来发布消息并处理这些消息。
Node.js 本身不支持 Web Worker,但可以在以下位置找到实现:
https://github。 com/cramforce/node-worker/
否则,它类似于以下代码:
childScript.js
You can use web workers to achieve your objective, but you'll require a separate js file, and you'll have to add plumbing code to post messages and handle those messages.
node.js doesn't support web workers natively, but an implementation is available at:
https://github.com/cramforce/node-worker/
Otherwise, it's similar to the following code:
childScript.js