Best method for linking asynchronous requests using axios

Is it possible to make an API call using axios based on the response of another initial API call, all within asynchronous functions?

I attempted the following approach with await/promise:

function fetchUserDetails(userId) {
  return axios.get( "https://apicall/" + userId )
}

function fetchUserPosts(username) {
  return axios.get("https://apicall/" + username)
}

var UsersOutput = async function () {
  const userDetails = await fetchUserDetails(2928928);
  const userPosts = await fetchUserPosts(userDetails.data.username);
  return { userDetails, userPosts }
}

However, this doesn't seem to return any data from either of the calls. Any advice would be greatly appreciated.

Answer №1

Your initial two functions are returning promises, not actual data. Consider using the following approach:

async function retrieveUser(value){
  return (await axios.get( "https://apicall/" + value )).data;
}

async function getUserPosts(username){
  return (await axios.get("https://apicall/" + username)).data;
}

If you prefer to keep the first two functions as they are:

var UsersOutput = async function () {
  const userProfile = (await retrieveUser(2928928)).data;
  const userPosts = (await getUserPosts(userProfile.data.username)).data;
  return { userProfile, userPosts }
}

In my opinion, the first option is better because the getter functions return objects instead of promises, reducing the need for (await ).data;. However, this is subjective and a matter of personal preference.

Answer №2

Have you considered checking out this helpful resource? https://javascript.info/async-await

Although you can use .then() in your case, I personally recommend utilizing async await.

With async functions and await keyword, you have the ability to chain various actions together and utilize the final result in your current context.

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

The outcome of the Javascript Calculator is showing as "Undefined"

I've been attempting to create a calculator using JavaScript, but I'm facing an issue where the 'operate' function keeps returning Undefined, and I can't seem to figure out why. I suspect that the problem lies with the switch state ...

Is there a way to remove CSS based on the generated HTML code?

Currently tackling a project in Next.js involving custom SCSS, Bootstrap SCSS, and React-Bootstrap. Struggling with the bloated size of our main.scss file due to unused CSS. After observing that 95% of the CSS is not utilized, I aim to eliminate all unnec ...

Struggling to prevent keyboard-triggered date changes in the MUI DatePicker API

Link to CodePen: codepen.io/s/jk3sgj?file=/demo.tsx Is there a way to prevent users from manually typing in dates and force them to select a date from a modal picker instead? I tried using the ReadOnly prop, but it disabled the entire input field, includ ...

function complete, ajax request finished

When working with Ajax to get data, I encountered a situation where I needed to return the value of `username` from within an if statement that is inside a loop and a function. How can I achieve this? Your help would be appreciated. $.ajax({ ...

Tips for accessing elements using document.getElementsByTagName

Greetings and best wishes for the holiday season! I hope everyone is cozy and safe. I need a little help with some code here, as I am fairly new to JavaScript but not entirely new to programming. Despite finding an answer on this site, I am still encounter ...

Issues arising with shadows in THREE.js

I've been struggling to get shadows to work in this fiddle despite trying various configurations. I've looked at other similar questions, tried all the suggested solutions, but still nothing... My current settings include: this._box.castShadows ...

What is the most effective way to manage and respond to multiple events while also organizing the overall structure of

I am currently in the process of planning a complex web application using WebGL and Three.js. As I experiment with different tests, I have encountered a problem that is raising many questions for me. I am unsure of the correct approach to take and would gr ...

The Ultimate Guide for Formatting JSON Data from Firebase

I'm facing an issue with parsing JSON data returned by Firebase. Here is the JSON snippet: { "-JxJZRHk8_azx0aG0WDk": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cda6a68daaa0aca4a1e3aea2a0">[email&# ...

Menu options are neatly displayed alongside video player without any overlap

I have included an object tag in my page to play videos: <object id="Player" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" data="mms://TAL-BBSR-01/01_Debugging.wmv" width="100%" type="video/x-ms-asf" height="400" wmode="opaque" url="mms://TAL-BB ...

After upgrading to version 4.0.0 of typescript-eslint/parser, why is eslint having trouble recognizing JSX or certain react @types as undefined?"

In a large project built with ReactJs, the eslint rules are based on this specific eslint configuration: const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1 module.exports = { ... After upgrading the library "@typescript-es ...

Creating a Social Media Platform with JavaScript, Bootstrap, JQuery, PHP, and Mysqil

I am currently in the process of developing a social networking platform that will have similar features as Instagram. Users will be able to log in, create posts, leave comments, like content, share posts, and send data to a server for storage or display p ...

Embed the website onto a webpage using ajax or an iframe without any need for navigation

I have a unique challenge ahead. Imagine there are two websites, one is a web page and the other is hosted within the same domain. My goal is to load the entire second website into a div or iframe of the first web page, similar to how a free proxy browser ...

How can I locally store 3D models and textures using three.js?

Currently working on a game using three.js, where each game level is on a different page. However, when transitioning from one level to another, the browser reloads the page which can be quite slow. Is there a way to store 3D models locally so they don&apo ...

What steps should I take to ensure a Vue 2/Vuetify form does not submit if the mandatory fields are left blank?

I developed a contact form using Vue 2/Vuetify 2 for a project I am working on. The form successfully submits to Strapi, the CMS that I am utilizing. However, despite having set rules and validation, it still submits with empty fields. The best progress I ...

Questions regarding prototype-based programming in Javascript

I am interested in achieving the following using Javascript: function A(){ this.B = function() { ... }; this.C = function() { <<I need to call B() here>> } ; }; I came across a method of method overloading, but I am curious to know ...

Allow frontend JavaScript to retrieve a text file that is restricted to individual users

Trying to articulate my goal is challenging, but I'll do my best to clarify. My objective is to enable JavaScript (or an alternative solution) to retrieve data from a text file on a static site and utilize that data in some way. The challenge here is ...

Adding JSON data to a MySQL column in JSON format with the help of NodeJS

I currently have a MySQL table set up with the following specifications: CREATE TABLE `WorkOrders` ( `workorder_id` int(11) NOT NULL AUTO_INCREMENT, `intertype_id` int(11) NOT NULL, `equipment_id` int(11) NOT NULL, `reason_id` int(11) NOT NULL ...

Securing API routes in Laravel

I have a Laravel application integrated with VUEJS for the front-end. I am retrieving data through API Routes. As an example, the route to fetch posts data is http://localhost/api/posts What would be the most effective method to secure my routes? After r ...

Refreshing and reloading within the same jQuery function

My PHP application involves the use of 2 PHP files. chart.php - This page includes a Google chart. <div id="chart_div" style="height:100%;width:100%"> </div> <script type="text/javascript"> google.charts.load('current', ...

"Null" is the value assigned to a JavaScript variable

I am encountering an issue on line 30 with the $.each(data.menu, function (). The console is indicating that "data is null". Can someone clarify what's happening? Thank you! function getFoodMenuData () { var url = 'http://localhost:88 ...