0

I have an axios function using GraphQL. It is a nested axios that is supposed to populate an object but is not. What is missing in my code?

My code:

const higher_fnc = (query_name) => {
  return axios({
    url: GraphQL_Endpoint,
    method: "post",
    headers: headers,
    data: query_name,
  });
};

higher_fnc({
  query: query1,
  variables: { id: "12345"},
}).then((d) => {
    for (const x of d.data) {
        const arr = [];
        for (const node of x.nodes) {
            const myObj = {};
            if (node.id === "56789") {
               higher_fnc({
               query: query2,
               variables: { id: "345545"},
               }).then((res) => {
                   for (const con of res.data) {
                        myObj["value"] = con.value;
                   }
               });
               myObj["id"] = node.node_id;
            } else {
               myObj["id"] = node.node_id;
               myObj["value"] = node.node_value;
            }
            arr.push(myObj);
        } 
        console.log(arr);
    }
});

myObj["value"] = con.value; in my code is not getting populated. What am I missing here? Everything is working fine, except that the value is not getting populated even though there is a value. How do I fix that?

nb_nb_nb
  • 1,243
  • 11
  • 36
  • It's most likely because the request in `axiosFunc` is async. Therefore the `for` loop completes long before the requests finish and your `then()` handler runs to set the `value` properties. You need to wait until ***all*** requests have completed. Better yet - don't make AJAX requests in a loop, as you're effectively DDOSing yourself. Make a single endpoint which accepts/returns all required data. – Rory McCrossan Aug 25 '23 at 14:52
  • @RoryMcCrossan, I am not sure how to do that. Can you give me an example? – nb_nb_nb Aug 25 '23 at 14:54

0 Answers0