Mastering Promises, Async/Await for managing the flow of execution

Exploring the concepts of promises, await, and async functions has been a fascinating journey for me. As I delved into promises, I discovered an interesting aspect - the unpredictable order in which requests were resolved when multiple requests were sent out simultaneously. Due to network routing and packet handling, the requests did not necessarily return in the same sequence as they were written in the code.

const getCountry = async country => {
  await fetch(`https://restcountries.com/v2/name/${country}`)
    .then(res => res.json())
    .then(data => {
      console.log(data[0]);
    })
    .catch(err => err.message);
};

getCountry('portugal');
getCountry('ecuador');

Before diving into the world of async and await, I found a solution that suited my needs perfectly. By incorporating these features, each request now waits for the previous one to complete before proceeding.

I wonder if there is a simpler way to achieve this? Are there any unnecessary redundancies that can be eliminated from the code? I am open to suggestions but prefer to stick with what works well for me.

  await fetch(`https://restcountries.com/v2/name/${country}`)
    .then(res => res.json())
    .then(data => {
      console.log(data[0]);
    })
    .catch(err => err.message);
};

const getCountryData = async function () {
  await getCountry('portugal');
  await getCountry('ecuador');
};

getCountryData();

Appreciate your input,

Answer №1

Absolutely, that method is spot on. Just bear in mind that by blocking each request you're sacrificing efficiency as they will run sequentially. One of the key advantages of JavaScript lies in its asynchronous nature, so it's best to leverage this feature. By running requests concurrently, you can significantly boost the speed of your requests. Consider the following example:

// fetching data...
const getCountry = async country => {
  const res = await fetch(`https://restcountries.com/v2/name/${country}`);
  const json = res.json();
  return json;
};

const getCountryData = async countries => {
  const proms = countries.map(getCountry); // generate an array of promises
  const res = await Promise.all(proms); // wait for all promises to resolve

  // extract the first value from the resulting array
  return res.map(r => r[0]);
};

// demonstration:
getCountryData(['portugal', 'ecuador']).then(console.log);
// sequenced based on input order
getCountryData(['ecuador', 'portugal']).then(console.log);
// retrieve multiple countries swiftly
getCountryData(['mexico', 'china', 'france', 'germany', 'ecaudor']).then(console.log);

Update: It has come to my attention that Promise.all handles promise ordering automatically, eliminating the need for an additional sorting function. Nevertheless, here is the sort function in case you opt for a different approach:

myArr.sort((a, b) => 
  (countries.indexOf(a.name.toLowerCase()) > countries.indexOf(b.name.toLowerCase())) ? 1 :
  (countries.indexOf(a.name.toLowerCase()) < countries.indexOf(b.name.toLowerCase())) ? -1 :
  0
);

Answer №2

Following @deceze's suggestion, I decided to take a different approach and it seems to be working smoothly: instead of using .then, I replaced them with await which makes the code much more concise. This way, I can now implement regular try and catch blocks for error handling.

// ARRANGE COUNTRIES IN SEQUENCE
const getCountry = async country => {
  try {
    const status = await fetch(`https://restcountries.com/v2/name/${country}`);
    const data = await status.json();
    renderCountry(data[0]); // Data is available. Let's Render HTML
} catch (err) {
    console.log(err.name, err.message);
  }
};

const getAllCountryData = async function () {
  await getCountry('portugal');
  await getCountry('Ecuador');
};

btn.addEventListener('click', function () {
  getAllCountryData();
});

A big thank you to everyone involved!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

``Passing a database value from a controller to a table popup through AJAX: A step-by

I need to display a popup containing data from a database. I'm using an AJAX function with onclick() to achieve this. The data retrieved will be shown in the popup, which includes a table. However, I'm unsure how to properly display the data with ...

Dynamically submitting a form generated within the AJAX success callback in CodeIgniter

After creating a form dynamically within the success function of an AJAX call, I expected it to submit like a normal form in CodeIgniter. However, upon clicking the submit button, the form data is not being picked up by the appropriate controller. The ori ...

Error: React/Express - The renderToString() function encountered an unexpected token '<'

As I work on implementing server-side rendering for my React/Express application, I have hit a snag due to a syntax error related to the use of the react-dom/server renderToString() method. In my approach, I am following a tutorial mentioned here - The sn ...

Fetching data using Axios from a specified URL

I am currently facing an issue with the npm package axios while attempting to execute a get request to a specific URL. The problem arises as I consistently receive an error code 503. Here is the snippet of code in question: let data, response; response = ...

Implementing Next.js in a live production environment

I've been using next.js for some time now, but I'm still trying to wrap my head around how it operates in a production environment. As far as I understand it, when a request is made to the server, the server retrieves the requested page from the ...

The communication between the Next.js and Node.js servers is being obstructed as the request body fails

Could you lend me a hand with this issue? Here is the function being called: function apiCreate(url, product) { console.log('Posting request API...' + JSON.stringify(product) ); fetch(url, { dataType: 'json', method: 'post ...

What is the correct way to invoke a function from a different file?

Having trouble calling a function from another file in my JS code. I am unable to call a function from another js file. I suspect there is an issue with linking the two files. Code snippet from my first JS file const { response } = require('expre ...

What causes an object to declare itself as undefined only in the event that I attempt to access one of its properties?

Check out this snippet of code: req.Course.find({}).populate('students', 'username firstName lastName registered').populate('teacher', 'image mID firstName lastName').sort({title: 1}).exec(function(err, courses){ ...

Saga Redux fails to pass parameters during post requests

This is my first time using redux Saga to handle API requests. I have created an async function for a simple post request in the following way: const onLoginRequest = async (userName, password) => await fetch(`${loginApi}`, { method: 'POST', ...

Sorting information in the React Native Section List

Working with React Native's SectionList and filtering data: data: [ { title: "Asia", data: ["Taj Mahal", "Great Wall of China", "Petra"] }, { title: "South America", data: ["Machu Picchu", "Christ the Redeemer", "C ...

Having trouble accessing PDF files on Electron framework

Despite following the advice provided in similar questions' answers, such as including webPreferences: { plugins: true } in the options when creating a BrowserWindow instance, I am still encountering issues. Every attempt to open or view a PDF ...

Encountering a problem when trying to pass a PHP array variable to a JavaScript function

I need some help with passing an array and input value from a form to a JavaScript function. The array, $quotes, contains posts. <form method="post"> <p>Search:<input type="text" name="qSearch" id="qSea ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

I will not be accessing the function inside the .on("click") event handler

Can someone help me troubleshoot why my code is not entering the on click function as expected? What am I missing here? let allDivsOnTheRightPane = rightPane.contents().find(".x-panel-body-noheader > div"); //adjust height of expanded divs after addi ...

JSON data is returned as Object Object

Trying to work with a JSON object and need to stringify it for localStorage: $http.post('http://localhost:8000/refresh', { name: $scope.name, email: $scope.email, token: $rootScope.devToken, platform: ionic.Platform.platform() }).then( ...

Transmitting PHP variable to JavaScript using Callback Method

I am looking to implement password validation using JavaScript along with an Ajax function. Upon successful validation, I aim to return a boolean variable (true or false) and perform specific actions in my PHP file based on the callback. Unfortunately, my ...

Is the initial carousel element failing to set height to 100% upon loading?

If you take a look here, upon loading the page you will notice a DIV at the top. It is labeled "content" with "content_container" wrapped around it and finally, "page" around that. Clicking the bottom left or right arrows reveals other DIVs with similar ta ...

Having trouble processing a JSON object using Jquery?

Hello, I am currently working on parsing a JSON object using jQuery. So far, I have successfully extracted all the necessary information from the results except for one crucial piece - the performance tags. Each JSON result is enclosed in an event tag and ...

Can you please identify the TypeScript type associated with the return value of the match() method in String prototype?

I need help with creating a Regex in JavaScript const pattern = /S(\d+)E(\d+)/; // identifying characters between "S" and "D" const result = 'SE01E09'.match(pattern); How should I declare the result variable? I have attempted various ...

A step-by-step guide on showcasing the content from a textfield onto a dynamic column chart

How can I show the value from a text field in a column chart? I found the code for the chart on this website(). I tried using the code below, but nothing happens. Can someone please assist me? <script> window.onload = function () { ...