masterofnone
masterofnone

Reputation: 13

Unable to await Axios call multiple times

Can someone explain to me why I am unable to perform consecutive axios API calls this way? I figured that since each call was awaited, then both calls would simply be treated the same way.

When I run this code, I get the following error: TypeError: parsedEmp is not iterable at Object.listEmployees

I do not receive the same error for the Axios call above it. Here's my code:

async function listEmployees() {
    const { data } = await axios.get('https://gist.githubusercontent.com/graffixnyc/febcdd2ca91ddc685c163158ee126b4f/raw/c9494f59261f655a24019d3b94dab4db9346da6e/work.json')
    const parsedData = data
    emp_data = []
    for(comp of parsedData) {
        emp_data.push([comp['company_name'],comp['employees']])
    }
    const { data2 } = await axios.get('https://gist.githubusercontent.com/graffixnyc/31e9ef8b7d7caa742f56dc5f5649a57f/raw/43356c676c2cdc81f81ca77b2b7f7c5105b53d7f/people.json')
    const parsedEmp = data2
    rosters = []
    for(entry of parsedEmp) {
        if(entry['id'] == e) {
            company.employees.push({ first_name: entry['first_name'], last_name: entry['last_name']})
        }
    }
    return rosters
}

Upvotes: 0

Views: 950

Answers (2)

NARGIS PARWEEN
NARGIS PARWEEN

Reputation: 1596

You can have the code like below

async function listEmployees() {
const { data: parsedData } = await axios.get('https://gist.githubusercontent.com/graffixnyc/febcdd2ca91ddc685c163158ee126b4f/raw/c9494f59261f655a24019d3b94dab4db9346da6e/work.json');
const { data: parsedEmp } = await axios.get('https://gist.githubusercontent.com/graffixnyc/31e9ef8b7d7caa742f56dc5f5649a57f/raw/43356c676c2cdc81f81ca77b2b7f7c5105b53d7f/people.json');

// get the employee details
let emp_data = [];
_.map(parsedData, (data) => {
    emp_data.push(data.company_name, data.employees);
});

// get the roster data
let rosters = [];
_.map(parsedEmp, (data) => {
    roster.push({ first_name: data['first_name'], last_name: data['last_name']});
});
return rosters;
}

Upvotes: -1

Phil
Phil

Reputation: 164739

Using destructuring assignment requires you to use the property names present in the source object, otherwise the resulting variables will be undefined. The Axios response object does not have a data2 property.

You would need something like this to access the data property

const response2 = await axios.get('https://...')
const parsedEmp = response2.data

or you can use this format to name the assigned variable

const { data: data2 } = await axios.get(...)
const parsedEmp = data2

or even this to save an extra line each time

const { data: parsedData } = await axios.get(/* first URL */)

// ...

const { data: parsedEmp } = await axios.get(/* second URL */)

Upvotes: 3

Related Questions