How do I make this JS function asynchronous?

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

    for (var i = 0; i

        
4条回答
  •  攒了一身酷
    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');
    

提交回复
热议问题