Search code examples
javascriptangularjscontentful

Async call inside loop


I have following code:

$scope.getEntriesBySpace = function(space, entryIds){
        var entriesHolder = [],
            errors = [];

        if(entryIds && entryIds.length > 0){
            angular.forEach(entryIds, function(entryId){
                space.cf_space.getEntry(entryId.trim()).catch(function(error) {
                    console.log('Could not find entry using access token, Error', error);
                    return error;
                }).then(function(response) {
                    if(response){
                        entriesHolder.push(data);
                    }else{
                        errors.push({"id": entryId, "message": "Entry not found"});
                    }
                });
            });
        }
    };

i call it like that:

$scope.getEntriesBySpace(sourceSpace, entries);

I want to store every response after each call finished inside the loop and return as array of responses or errors.

Any help is appreciated.

Method getEntry returns promise.

For ref see this library: https://github.com/contentful/contentful-management.js

Thanks


Solution

  • So there's two ways of doing this. When you have promises, you also generally page a Promise.all method which is part of the promise implementations. In Angular, you'd do $q.all.

    So then you can do something like:

    $q.all(entryIds.map(function(entryId){ return space.cf_space.getEntry(entryId.trim()) })) .then(function(entries){ console.log(entries) })

    However, it seems like you're using the contentful SDK, where you also have a getEntries method which has query parameters which allow you to get more than one entry at once in one request. This would be the most desirable thing because it would be much faster.

    space.cf_space.getEntries({'sys.id[in]': entryIds.join(',')}) .then(function(entries){ console.log(entries) })