Difference between Javascript async functions and Web workers?

后端 未结 6 1489
南笙
南笙 2021-02-05 06:53

Threading-wise, what\'s the difference between web workers and functions declared as

async function xxx()
{
}

?

I am aware web worker

6条回答
  •  后悔当初
    2021-02-05 07:43

    Here is a way to call standard functions as workers, enabling true parallelism. It's an unholy hack written in blood with help from satan, and probably there are a ton of browser quirks that can break it, but as far as I can tell it works.

    [constraints: the function header has to be as simple as function f(a,b,c) and if there's any result, it has to go through a return statement]

    function Async(func, params, callback)
    { 
     // ACQUIRE ORIGINAL FUNCTION'S CODE
     var text = func.toString(); 
    
    
     // EXTRACT ARGUMENTS
     var args = text.slice(text.indexOf("(") + 1, text.indexOf(")")); 
     args     = args.split(",");
     for(arg of args) arg = arg.trim();
    
    
     // ALTER FUNCTION'S CODE:
     // 1) DECLARE ARGUMENTS AS VARIABLES
     // 2) REPLACE RETURN STATEMENTS WITH THREAD POSTMESSAGE AND TERMINATION
     var body = text.slice(text.indexOf("{") + 1, text.lastIndexOf("}")); 
     for(var i = 0, c = params.length; i

    So, assuming you have this potentially cpu intensive function...

    function HeavyWorkload(nx, ny) 
    {
     var data = [];
    
     for(var x = 0; x < nx; x++)
     {
      data[x] = [];
    
      for(var y = 0; y < ny; y++)
      {
       data[x][y] = Math.random();
      }
     }
    
     return data;
    }
    

    ...you can now call it like this:

    Async(HeavyWorkload, [1000, 1000],
    function(result)
    {
     console.log(result);
    }
    );
    

提交回复
热议问题