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:
- 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.
- Promises are the more modern way to deal with asynchronicity.
setTimeout()
uses "old-school" callback-style asynchronicity, andfs.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()
, orutil.promisify
in Node.js. - You can also callback-ify promise-style asynchronous functions, but in general you don't need to.
- You can promisify callback-style asynchronous functions by hand by using