4

Really trying to understand the event queue of javascript. My current understanding is the following.

Code:

let doSomething = (callback) => {
callback("first");
};

let foo = (text) => {
    console.log(text);
};

doSomething(foo);

setTimeout(() => {
    console.log("hey");
});

console.log("after");

Current knowledge:

The callback of doSomething is not an asynchronous operation so it is not placed in the callback queue. However, the setTimeout is an asynchronous operation and thus placed in the callback queue this. Because the callback queue is called upon after the javascript thread is finished, thus the setTimeout() function is called last.

Questions:

  1. Is my current understanding correct?
  2. What exactly makes an operation an asynchronous operation? Is this because Javascript itself has certain operations which are asynchronous by default?
  3. Can you make asynchronous operations yourself in javascript without the use of built in asynchronous operations like setTimeout()?
Mouser
  • 13,132
  • 3
  • 28
  • 54
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
  • Yes, [Yes](https://stackoverflow.com/q/19083357/1048572), [No](https://stackoverflow.com/q/22286887/1048572). – Bergi Oct 08 '17 at 13:22

1 Answers1

5

Is my current understanding correct?

Yes, it will execute those functions in order. Since you call doSomething before you define the setTimeout it will finish first.

What exactly makes an operation an asynchronous operation? Is this because Javascript itself has certain operations which are asynchronous by default?

It is asynchronous when the execution of the code doesn't halt the execution of the main thread. JavaScript is single threaded. xmlHTTPRequests, intervals and timeouts are examples of asynchronous functions. Events are asynchronous too. But as you said, they are all built-in.

Can you make asynchronous operations yourself in javascript without the use of built in asynchronous operations like setTimeout()?

In the old days not so easy. As I said, you can make custom events and web workers. Nowadays:

Mouser
  • 13,132
  • 3
  • 28
  • 54