问题
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);
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.
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:
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 therequest
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 theworker_threads
module in more recent node versions.The
async
keyword isn't required for a function to be asynchronous. Marking a function asasync
lets the function use theawait
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