+ 1
outside of Api requests, what would be considered a asynchronous action in javascript.
Web development
2 Respostas
+ 2
Depends on what you mean by asynchronous action. In principle your code starts at the top of your script tag and then runs line by line top to bottom, and anything that happens adjacent to this would be considered asynchronous or concurrent.
For example:
- Someone clicked a button and an event handler triggered.
button.addEventListener(...);
- You loaded an image.
const img = new Image();
img.onLoad = () => { ... };
- A timer expired.
window.setTimeout(...);
async/await is a fairly new construct in javascript so it's not used everywhere where it would potentially make sense. I like to async-ify things by hand, especially UI stuff and timers, because `await timeout(1000)` just feels so much nicer.
+ 1
all that requires callbacks (and all the more a lot of chained callbacks) could benefit to using asynchronous tasks: that's more readable, and from a certain point of view easier to handle/write (despites the fact that mastering promises/async/await should not be so easy ^^)...
to convince yourself, you could read this article: https://www.toptal.com/javascript/asynchronous-javascript-async-await-tutorial
even if it use html requests to demonstrate: that's the most obvious use of async features ^^
however, anything that require lot of computation could also benefit from async implementation, even if in single threaded js, it must be a few hard to not be blocking: you must split your code in micro tasks wich are executed by calling them through timeout (to let browser time to refresh display refresh and treat user interactions) wrapped inside promises ^^
but a more efficient way to handle heavy computations are web workers: they are non-blocking as running their own threads... if you avoid access dom ;P