0

I get undefined when i try to console.log it

var farr = [];
$.ajax({
    url: "https://whispering-cliffs-33347.herokuapp.com/employees",
    type: "GET",
    contentType: "application/jsonp"
}).done(function(employees) {
    for(let i in employees){
        farr.push(employees[i]);
    }
})
console.log(farr[8]);

Any ideas?

Brandon
  • 1
  • 1
  • First console `employees`. Know whether it is array or object. If it is array, you may need to parse the JSON. And use console in `.done` function. – Harish Kommuri Feb 04 '18 at 05:24
  • 1
    Move the `console.log` call into your `.done()` callback. Remember that `$.ajax` is asynchronous and any return values or variables you're setting in the callback will be undefined outside of the callback. – user9263373 Feb 04 '18 at 05:27
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Hassan Imam Feb 04 '18 at 05:29
  • just use async:false – Hossein Badrnezhad Feb 04 '18 at 05:30
  • 1
    No, do not use `async:false`. It's deprecated, it's lazy and it's poor programming practice. – user9263373 Feb 04 '18 at 05:32

2 Answers2

1

console.log(farr[8]); will be executed even before the response is available.So in first done push all the elements in the local array & once that is done in the next done log the value

var farr = [];
    $.ajax({
        url: "https://whispering-cliffs-33347.herokuapp.com/employees",
        type: "GET",
        contentType: "application/jsonp"
    }).done(function(employees) {
        employees.forEach(function(item){
            farr.push(item)
        })
    }).done(function(elem){
        console.log(farr[8]);
    })
brk
  • 48,835
  • 10
  • 56
  • 78
0

You can not iterate the object with standard for loop. To be able to do that, you should first get object keys in an array and iterate over that.

const keys = Object.keys(employees);
keys.forEach((i) => {
     farr.push(employees[i]);
 }
 console.log(farr[8]);. // You should put this in the call back itself

Or you can directly iterate over the object using lodash's forEach.

Aaditya Thakkar
  • 1,750
  • 13
  • 13