1

I'm trying to create an array of data which I get from an API. As a searched here, due to the asynchronous nature of the get request I should use a callback function to make this work. I managed to create it and alert or console.log the result. The function is this (no need to show the complete implementation):

loadData(function(result){
    console.log(result); // prints correct result
});

This result seems to be just a reference. How can I assign the result to a global variable in order to use it in my code together with other variables? By the way the result is an array. So I want to make an array from the result that I can use in different ways. Is my logic totally wrong?

  • If you're trying to make an assignment inside the callback and then use the global variable **outside** the callback, then yes your logic is totally wrong :) At least, it's wrong if the API is asynchronous, which is very common in JavaScript. – Pointy Dec 16 '15 at 19:39
  • @Pointy Thanks. This is the post I read in order to create my callback function. I was able to console.log exactly what I wanted. But it doesn't mention if we could make an assignment. – Dimitrios Vythoulkas Dec 16 '15 at 19:43
  • You definitely can make the assignment. The tricky part is knowing outside the callback when it's safe to use the result of the assignment. – Pointy Dec 16 '15 at 19:59
  • @Pointy I don't know the way and since my question is marked as a duplicate I guess I'll never find out. – Dimitrios Vythoulkas Dec 16 '15 at 20:03

0 Answers0