如何使这个JS函数异步? [英] How do I make this JS function asynchronous?

查看:82
本文介绍了如何使这个JS函数异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function takesTime(){

    for (var i = 0; i<some_very_large_number; i++){
        //do something synchronous
    }
    console.log('a');
}

takesTime();
console.log('b');

这打印:
a
b
你会如何打印:
b
a

This prints: a b How would you make it print: b a

推荐答案

我看到这是标记为node.js,所以我将从那个观点:你不应该。通常,如果您阻止,它将是:网络绑定(您应该使用和/或重用围绕异步方法的网络库),I / O绑定(你应该使用和/或重用 I / O库)或CPU绑定。你还没有为长期运行的任务提供任何上下文,并且假设你有一个包含 some_very_large_number 的循环不变量,我假设你在想象一些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.

如果你实际上是CPU限制的,你应该重新考虑你的策略。节点只存在于一个核心上,所以即使你能够使用多线程,你也只是在转动轮子,因为每个请求仍然需要一定的CPU时间。如果您真的打算做一些计算密集型的事情,您可能需要考虑使用排队系统,还有其他处理数据的东西,这些数据更适合用于处理它。

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.

这篇关于如何使这个JS函数异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆