Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
Unable to get the required object returned from the callback function

I am trying to return the required object from the objects array where the array index is passed as a parameter to the callback function. E.g. if I want the object at array index 0 I call getInfo this way getInfo(0, data). But the callback function only returns the index back and not the value. I tried to test the same with simple function called myfunc but that gives me what I want. What's the issue over here?

This is my code

const getInfo = (resource, callback) => {
let request = new XMLHttpRequest();

    request.addEventListener('readystatechange', () => {
        if(request.readyState === 4 && request.status === 200 )
            {
                const data = JSON.parse(request.responseText);
                console.log(data[resource]);
                myfunc(resource, data[resource]);
                callback(resource, data[resource]);
            }
    });

    request.open('GET','values.json');
    request.send();
};

const myfunc = (val,arr) =>{
    console.log(val,arr);
}

getInfo(0, data => {
    console.log(data);
    getInfo(2, data => {
        console.log(data);
        getInfo(1, data => {
                console.log(data);
        });
    });
});

values.json

[
    {"name" : "MM", "height" : "5 ft 2 inches"},
    {"name" : "DD", "height" : "5 ft 3 inches"},
    {"name" : "AA", "height" : "5 ft 5 inches"}
]

Console Output

enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you callback has only one parameter, but you are sending two arguments when calling the callback

getInfo(0, (index,data) => {
    console.log(data);
    getInfo(2, (index,data) => {
        console.log(data);
        getInfo(1, (index,data) => {
                console.log(data);
        });
    });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!