- JavaScript Promises and
async/awaitare powerful features that enable developers to handle asynchronous operations in a more organized and readable way. Prior they were introduced, developers need to write a lot of callback functions. The following code will fail because the response object does not exist.
const axiosRequest = require('axios') let response = axiosRequest.get("https://www.boredapi.com/api/activity") console.log(`You could ${response.data.activity}`)- Is there any way for us to get access to the result of the request and run code when it returns?
To solve this problem, JavaScript gives us a few ways to wait until a task is finished so we can use the result or catch any error that occur.
What if there is an error?const axiosRequest = require('axios') axiosRequest .get("https://www.boredapi.com/api/activity") .then(response => { console.log(`You could ${response.data.activity}`) )) .catch(error => { console.error(`ERROR ! ${error}`) }); // OUTPUT // You could Volunteer at a local animal shelterconst axiosRequest = require('axios') axiosRequest .get("https://httpstat.is/404") .then(response => { console.log(`You could ${response.data.activity}`) )) .catch(error => { console.error(`ERROR ! ${error}`) }); // OUTPUT // ERROR! Error: Request failed with status code 404The examples above introduce a problem where code is not execute sequentially. For example: “Why am I here” is executed first.
const axiosRequest = require('axios') axiosRequest .get("https://www.boredapi.com/api/activity") .then(response => { console.log(`You could ${response.data.activity}`) )) .catch(error => { console.error(`ERROR ! ${error}`) }); console.log("Why am I here")The
awaitkeyword was introduced to solve this problem. According to the mozilla site, the await operator is used to wait for a Promise. It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.
The console log line will not run until the promise resolves or is returned.const axiosRequest = require('axios') async function getActivity() { let response = await axiosRequest.get("https://www.boredapi.com/api/activity") console.log(`You could ${response.data.activity}`) } getActivity(); // OUTPUT // You could Volunteer at a local animal shelterHowever, if there is any error occur, we would need to catch the error. Since await allows our code execute sequentially, now we can use
try()andcatch()block like the following:const axiosRequest = require( 'axios') async function getActivity () { try { let response = await axiosRequest.get ( 'https://httpstat.us/500') console. log ('You could ${response data.activity}') } catch (error) { console.error ('ERROR: ${error}') } } getActivity () // OUTPUT // ERROR: Error: Request failed with status code 500
