I am using AngularJS here, but if you have a more generic answer I’ll be glad to know about it.
I have an array of elements containing ids
myArray = [{
id: 0,
foo: "foo"
}, {
id: 1,
bar: "bar"
}]
And a service to ask informations using those ids, which take as arguments an object of informations (for the request), and two callbacks, one for success and one for error (both are not required).
Service.getInformations({id: 1}, onSuccess, onError)
What I would like to do is something like this:
myArray.map(function (element){
Service.getInformations({id: element.id}, function(data) {
return data; // here is the issue
})
});
The issue here is that I am returning data in service callback function and not in map callback function. I am struggling to find some good way to do it.
Chaining asynchronous functions is a tricky old problem. Here's a way of doing it in Vanilla Javascript (with or without Angular):
Here's a simple example that you can try without Angular:
You could do something like this, using built in $q service on angular.
You can iterate over the elements, make a call to the service and return a promise and execute the callback only when all async operations are complete.
In this case callback takes an array of results from their respective calls.