I suspect it’s an issue with asynchronousity,
I just can’t get my head around what’s the problem.
So I make multiple api requests and fill a list with the responses.
Then I have a D3.js script charting the data,
which receives undefined though, I substituted it with a simple log here.
(of course the console “evaluates” the values later in real-time, but logging a nodes[0] item is indeed undefined.)
I tested setting a timeout to the subsequent scripts but no avail,
and I couldn’t come up with a callback solution since the request
is itself a callback already.
(I know forEach
is the proper method to use here, but I’m also trying to get the assignment functional with an immediate return, which is also something I couldn’t yet make happen)
variables=["pageid1","pageid2","pageid3"];
nodes=[];
variables.map(function(variable){
FB.api("/"+variable,"GET",{fields:'name,picture.type(large),engagement'},function(response){
if(!response.error){
nodes.push(response);
}
});
});
console.log(nodes);
3
Answers
Yes, of course, your console.log can and will fire before the
.api
finishes. Trying to delay it with asetTimeout
is just bad programming (it’s a guessing game).Any processing on
nodes
needs to be within the.api
callback. If you are firing multiple async calls and need them all to finish before processingnodes
you should be using something like d3.queue. From the docs (bolding mine):In your case the code might look like this (untested):
You can wrap the requests in a promise. then wait for all the promises to be resolved in which case you will have your nodes variable filled with responses.
you can do it like so:
Different approach with async/await and some fixes (let, arrow functions, …):