简体   繁体   中英

Callbacks as Objects - how it relates to asynchronous programming in JavaScript

I've been reading about callback functions here , and learned that JavaScript is a single-thread synchronous language.

This means that if you want to collect data from a database then you'd have to wait for the routine to finish before any more code was executed. Is this true? What would happen if the user pressed a button to call a different function in the same script file?

To make it asynchronous you can use callbacks. Asynchronous here would mean that a section of code in the callback would 'wait' for an event before being called but a new thread is not created.

What is it about being an Object that makes JavaScript callbacks asynchronous?

It is the same as waiting for an event?

It is true that with Javascript, if you are going to call into a database, generally you must wait for the database to respond (ie, a round trip to Pluto ) before your code will continue to execute. This is called a 'blocking' call.

What a callback allows you to do is make a blocking call, but as you do so also say, "Execute this code when the blocking call concludes, but don't wait around for that to happen." Thus, your program continues execution. When the blocking call completes, the code you specify in the callback (which has not been run yet) will then execute. This may be almost immediately or some time later.

With Javascript, the rest of your code will complete execution, then the first callback to be triggered by a blocking call finishing will be executed, and so on until all callbacks are executed. At that point the thread will be shut down.

Note that only the callback code is 'waiting for an event'.

Thus, the execution order looks something like this:

  1. Execute some code.
  2. Set up callback code.
  3. Execute blocking call.
  4. Execute remainder of code.
  5. Wait for blocking call to return.
  6. Execute callback code.
  7. Stop thread process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM