Home > Software engineering >  What makes the requests/functions in Javascript asynchronous?
What makes the requests/functions in Javascript asynchronous?

Time:09-23

When you make a request to an API, the operation is usually asynchronous. I am wondering what actually makes these API requests asynchronous? Is it because we send the requests asynchronously(like using .then() function or async/await for promise) or the API server handles our requests asynchronously? I think it should be the former one? Besides, why some functions can be asynchronous without promise(such as setTimeout() and fs.readFile())?. Thanks!

CodePudding user response:

  1. The JavaScript runtime (e.g. Node.js or the browser) arranges for the request to be sent asynchronously, i.e. so your code gets notification of its progress or completion out of the usual order of code execution. What the server on its end does has nothing to do with it.
  2. Promises are the more modern way to deal with asynchronicity. setTimeout() uses "old-school" callback-style asynchronicity, and fs.readFile() uses Node.js's own brand of callback asynchronicity, where by convention the first argument of the callback is an error, if any occurred.
    • You can promisify callback-style asynchronous functions by hand by using new Promise(), or util.promisify in Node.js.
    • You can also callback-ify promise-style asynchronous functions, but in general you don't need to.
  • Related