2019-05-27
What is Asynchronous?
Asynchronous usually happens when we are interacting with a database or API.
The term asynchronous can be a bit difficult to explain. To understand it, let's take a look at what synchronous
is, more specific, what synchronous task is.
In programming, synchronous task is a task that is executed in sequence, meaning that it will wait for current task to be finished before the next task is executed.
On the other hand, Asynchronous task or we can call it async
task can continue executing the next task without waiting for the current task to be finished first.
Then why do we use async? We can understand it more simple using an example: If we have a page that needs to load a set of images, if we do it synchronously, the page will looks like it's frozen and the user will wonder what is going on. But if we do it with async method, we can show a loading spinner while the images are being loaded from the database. So async gives benefit of responsiveness, the user can still interact or in the above case, see interaction while waiting the task finished.
There are two popular methods for handling async task:
With Promise, we use callback function such as .then for success result and .catch for error result.
const getRequest = () =>
fetchData()
.then(data => {
console.log(data);
return data;
})
.catch(error => console.log(error.message));
With Async-await, we use it just like writing synchronous code with try catch block.
const getRequest = async () => {
try {
const data = await fetchData();
console.log(data);
return data;
} catch (error) {
console.log(error.message);
}
};
Which method is better? That depends on how complex or complicated the async task is, if the async task requires chaining several promises together, rather than nesting several .then functions, it is better to write it using async-await as it will make the code more readable.