0

I have the following code for getting the length of an array using an Ajax call. A callback is used here. However, I keep getting [object Object] instead of the actual count. What am I doing wrong?

var count = countArray().done(handle_countArray);   

alert(count); // shows [object Object]



function handle_countArray(array) {
    var count = array.length;
    alert(count); // gets correct length

    return count; // should return correct length
}

function countArray() {
    return $.ajax({ url: "..." });
}
  • - asynchronicity – Igor Apr 27 '17 at 21:22
  • Can you `console.log(array)` and paste the output here? – AP. Apr 27 '17 at 21:22
  • @Igor isn't that what the `done()` callback is for? – AP. Apr 27 '17 at 21:22
  • @Igor I thought callbacks are supposed to fix that? –  Apr 27 '17 at 21:22
  • @AP., jebmarcus_returns - no, `done` still returns the same `xhr` object as `$.ajax`. That's why you can chain-call `done`, `fail`, `always` etc. – Igor Apr 27 '17 at 21:23
  • @AP. console.log(array) inside the `handle_countArray` function returns `[Object, Object, Object, Object]` –  Apr 27 '17 at 21:25
  • @Igor I didn't notice the assignment to `count` – AP. Apr 27 '17 at 21:26
  • @igor this doesn't make sense because done() is designed to fix asynchronous issues? no? –  Apr 27 '17 at 21:26
  • @jebmarcus_returns haha, no. it just allows you to apply a callback. Within said callback, you can access the results. You cannot however return those results back to the outside because the outside has already finished. – Kevin B Apr 27 '17 at 21:26
  • @jebmarcus_returns You cannot assign count synchronously in this case. Use count inside your `handle_countArray` callback – AP. Apr 27 '17 at 21:27
  • @jebmarcus_returns - depends on what your understanding of "fix" is. – Igor Apr 27 '17 at 21:27

0 Answers0