Threading-wise, what\'s the difference between web workers and functions declared as
async function xxx()
{
}
?
I am aware web worker
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.