How are callbacks coded in Javascript, behind the scenes?

扶醉桌前 提交于 2021-01-29 22:11:18

问题


How does a function know that something is a callback; something that needs to be executed once certain prior I/O has completed. How does it know that it shouldn't execute right away? Is it defined in a function in a (standardized) way?

As far as I know the 'callback' keyword that is often used in an argument is just common practise, but does not automatically let the function interpret the argument as something that should start once certain I/O has completed.

Taking the below example, I have two questions (taken from https://medium.com/codebuddies/getting-to-know-asynchronous-javascript-callbacks-promises-and-async-await-17e0673281ee):

const request = require(‘request’);
function handleResponse(error, response, body){
    if(error){
        // Handle error.
    }
    else {
        // Successful, do something with the result.
    }
}
request('https://www.somepage.com', handleResponse);
  1. What does the structure of the 'require' function look like so that it knows that argument 2 (handleResponse in this case) should be executed once the request has completed? I guess this gets down to the same question that I asked above.

  2. Can functions be asynchronous even without the async keyword in the function? If yes, how does the browser know it's an asynchronous function?


回答1:


  1. I assume you meant to ask about the request function. Most asynchronous functions call other asynchronous functions to do some work, and then call the callback. You can think of it as a chain of functions and callbacks. This is what the request function does. Of course, at least the last function needs to be truly asynchronous, and usually that is a function exported by one of the node built-in modules (fs, http, ...). It may also be exported by a native module, or using the worker_threads module in more recent node versions.

  2. The async keyword isn't required for a function to be asynchronous. Marking a function as async lets the function use the await syntax and makes the function return a Promise implicitly.

To better understand how asynchronous code works, you should take a look at how the node event loop works

Note that I assumed a Node.js environment, because you used require, but most of what I said applies to the browser as well: there is a chain of asynchronous functions, and the last one will call one of the built-in functions (for instance XMLHttpRequest). The browser environment uses an event loop too, and async/await work in the same way



来源:https://stackoverflow.com/questions/58462670/how-are-callbacks-coded-in-javascript-behind-the-scenes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!