JavaScript Callbacks: Asynchronous or Not?
JavaScript callbacks are not universally asynchronous. In certain scenarios, such as the example you provided with the addOne and simpleMap functions, the code operates synchronously.
Asynchronous JavaScript in the Browser
Callback-based AJAX functions in jQuery are often asynchronous because they involve XHR (XMLHttpRequest) requests. By default, XHR requests in browsers are asynchronous, allowing ongoing script execution while the request is being processed.
Asynchronous JavaScript in Node.js
In Node.js, asynchronous behavior generally arises from input/output (I/O) operations, such as file I/O, process.nextTick, setTimeout, and setInterval. Callback-based database calls with MongoDB/Mongoose are asynchronous due to the underlying I/O operations involved in interacting with the database.
Predetermined Asynchronous Situations
Asynchronicity is often ingrained in the environment. In the browser, callback functions associated with XHR requests are inherently asynchronous. In Node.js, callbacks linked to I/O operations are likewise asynchronous.
Custom Asynchronous Functions
Without relying solely on specific environmental functions, you can achieve asynchronous behavior by leveraging ES6 promises. Promises provide a language-level mechanism for defining asynchronous operations. The callback functions attached to promises (via then and catch) are always executed asynchronously, ensuring that the code following the promise doesn't block.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3