Difference between Javascript async functions and Web workers?

后端 未结 6 1492
南笙
南笙 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:47

    Async functions have nothing to do with web workers or node child processes - unlike those, they are not a solution for parallel processing on multiple threads.

    An async function is just1 syntactic sugar for a function returning a promise then() chain.

    async function example() {
        await delay(1000);
        console.log("waited.");
    }
    

    is just the same as

    function example() {
        return Promise.resolve(delay(1000)).then(() => {
            console.log("waited.");
        });
    }
    

    These two are virtually indistinguishable in their behaviour. The semantics of await or a specified in terms of promises, and every async function does return a promise for its result.

    1: The syntactic sugar gets a bit more elaborate in the presence of control structures such as if/else or loops which are much harder to express as a linear promise chain, but it's still conceptually the same.

    Are such functions threaded in the same way as a function executed through setInterval is?

    Yes, the asynchronous parts of async functions run as (promise) callbacks on the standard event loop. The delay in the example above would implemented with the normal setTimeout - wrapped in a promise for easy consumption:

    function delay(t) {
        return new Promise(resolve => {
            setTimeout(resolve, t);
        });
    }
    

提交回复
热议问题