简体   繁体   中英

async programming - how to loop through an array of objects and change a property to each object with data fetched from an api?

So I have an array of object similar to this:

[ { id: 123, info: 'text', number: 0 }, ... ]

I have an API that takes the ID of the object and returns a number associated with it. On a front end app using JavaScript, I want to iterate over each object in the array, and populate that number property with data from this API.

I am using AngularJS and this is the function I wrote that fetches the number associated with each object:

    $scope.getNumber = function(id) {
        $http.get('/api/getnumber/' + id)
            .success(function(data) {
                console.log(data.goings);
                return data.number;
            });
    }

this function works. My problem is I don't know how to update the number property in each object in the array. I've tried looping over it, but this doesn't work as the loop executes before .get() is done fetching data. I've also tried in an html to have the following code:

<div ng-repeat="obj in data">
      {{ getNumber(obj.id) || 0 }}
</div>

But this creates an infinite loop which crashes my browser. I tried doing some searching but I'm having trouble finding a comparable case. How can I achieve this?

$http.get(..).success(..) returns a promise, hence can't be used this way. Maybe load all numbers when controller loads and attach it to data?

As has been said, the success() function simply returns another promise, and isn't in itself the value you want. Returning a value like you do, in a success function, is only useful as a way to pass the result on to another promise when you're chaining them.

If these values might change as the user interacts with the page, the best option is to have a scope variable (your array being iterated over with ng-repeat works) that constantly displays, and is updated by the $http promise.

If you only expect it to be one thing each time the page loads, you can pre-load them with resolves (for resolves with UI-router, look here ). Resolves let you make promise calls before a page loads, and only start loading the actual page once the promises all resolve.

You may have a call for retrieving the numbers you need in bulk, but if not, you can turn the individual calls into a group resolve by using $q.all() , which allows you to provide an array of promises and get back an array of their results.

Of course, if you want to load them ahead of time, and then modify them during the course of the page's lifespan, you can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM