Difference between Javascript async functions and Web workers?

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

    In contrast to WebWorkers, async functions are never guaranteed to be executed on a separate thread.

    They just don't block the whole thread until their response arrives. You can think of them as being registered as waiting for a result, let other code execute and when their response comes through they get executed; hence the name asynchronous programming.

    This is achieved through a message queue, which is a list of messages to be processed. Each message has an associated function which gets called in order to handle the message.

    Doing this:

    setTimeout(() => {
      console.log('foo')
    }, 1000)
    

    will simply add the callback function (that logs to the console) to the message queue. When it's 1000ms timer elapses, the message is popped from the message queue and executed.

    While the timer is ticking, other code is free to execute. This is what gives the illusion of multithreading.

    The setTimeout example above uses callbacks. Promises and async work the same way at a lower level — they piggyback on that message-queue concept, but are just syntactically different.

提交回复
热议问题