Home > other >  Unable to get the required object returned from the callback function
Unable to get the required object returned from the callback function

Time:11-06

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

CodePudding user response:

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);
        });
    });
});
  • Related