How do I make this JS function asynchronous?

后端 未结 4 895
时光说笑
时光说笑 2021-02-04 02:58
function takesTime(){

    for (var i = 0; i

        
相关标签:
4条回答
  • 2021-02-04 03:01

    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.

    0 讨论(0)
  • 2021-02-04 03:03

    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()).

    0 讨论(0)
  • 2021-02-04 03:04

    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:

    var pid = require('child_process').spawn('node', ['childScript.js'])
    pid.stdout.on('data', function(data) {
      console.log(data);
    });
    console.log('b');
    

    childScript.js

    for (var i = 0; i < some_very_large_number; i++) {
      // do something synchronous
    }
    console.log('a');
    
    0 讨论(0)
  • 2021-02-04 03:16
    for (var i = 0; i < someVeryLargeNumber; ++i) {
        setTimeout(function () {
            //do something synchronous
        }, 0);
    }
    

    Also see setZeroTimeout to gain a few milliseconds each loop, although the work people are doing there seems to be browser-based.

    0 讨论(0)
提交回复
热议问题