Asynchronous vs Synchronous code?
Synchronous code is code that blocks the execution of code till the line has been executed, meaning that the program will wait for a task to complete before moving on to the next one. This is in contrast to asynchronous code, which allows for multiple tasks to be executed in parallel.
Asynchronous code refers to code that runs independently of the main program flow, allowing the program to continue executing while the asynchronous code runs in the background. This can be useful for tasks that take a long time to complete, such as fetching data from a server or performing a complex calculation.
In which situations does asynchronous code help us?
Assume you write a code, and a line in code makes a request to a server, but the server is very slow and takes a minute to return a response. You might have noticed the problem with this, which is, for the whole minute your code will not be doing any other tasks, won't take new requests from users, and will waste resources.
This could be solved in asynchronous code, which will allow your code to keep running in parallel
Libraries helpful in calling APIs
Axios and fetch are among the several libraries that allow you to make asynchronous requests. The way these work is they return a promise that represents the response from an API, which in simpler words means your code keeps running parallelly, and whenever the promise is resolved you can access its value
How to resolve the promise or wait for it?
Node.js provides two primary ways to work with promises:
Using .then()/.catch()
Using aync/await
Both of these work efficiently, but out of these async/await is the newer concept, and provides a more readable and easy-to-understand code, thus I would recommend using it.
Using async/await to call asynchronously:
The key to making the API call asynchronous is to use the await
keyword, which allows you to wait for the API call to complete before continuing with the rest of your code.
- A logical question that comes to mind now is if we are using await keyword to wait for the execution of code then how is it asynchronous?
In javascript to use await in a function, the function must be declared with async. The async keyword is used to indicate that a function returns a promise and that you can use the await keyword within the function to wait for the promise to resolve.
So you need to think of it like this within the program the function that is using await keyword is asynchronous, so other stuff can be done in the background. But within the function itself, it will wait for the promise to be fulfilled before proceeding with the code.
Example code:
Here i am using Axios library to make the get request to an API, that returns the current price of bitcoin.
// First, install the axios library using npm:
// npm install axios
// Then, include the library in your code:
const axios = require("axios");
const fetchPrice = async() =>{
const API_URL = "https://api.coindesk.com/v1/bpi/currentprice.json";
const price = await axios.get(API_URL);
console.log(price.data);
}
fetchPrice()
console.log("This line occurs after calling the funcion, but is printed before the functions data");
In the above example, the function is called first fetchPrice(), then there is a console.log statement. But in the output, you can see that console.log() was executed before the API data.
Error Handling
When using APIs there are n number of things that can go wrong, and a good code should make sure that it handles errors generated during the code execution, A good way to do this is using try, and catch block
The try block will hold the main part of your API call and further steps, and the catch block holds the code that needs to be run in case an error occurs while calling the API
// First, install the axios library using npm:
// npm install axios
// Then, include the library in your code:
const axios = require("axios");
const fetchPrice = async() =>{
try{
const API_URL = "https://api.coindesk.com/v1/bpi/currentprice.json";
const price = await axios.get(API_URL);
console.log(price.data);
}catch(error){
console.log("A error was encountered " + error);
}
}
fetchPrice()
console.log("This line occurs after calling the funcion, but is printed before the functions data");