1

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

maverickosama92
  • 2,685
  • 2
  • 21
  • 35
  • 1
    Sounds like this http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – elclanrs Mar 11 '16 at 15:18
  • @Hacketo: How would i store every response in an array and return at the end of all the calls are finished? – maverickosama92 Mar 11 '16 at 15:20
  • @elclanrs: I have tried that solution. But it didnt work I need to have all responses at once. So that i can further do processing on them. Kindly help me here I'll be very grateful. Thanks – maverickosama92 Mar 11 '16 at 15:32

3 Answers3

1

You can use the lib async for that: https://github.com/caolan/async

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

    var fn = function(entryId, callback){
          space.cf_space.getEntry(entryId.trim())
              .catch(function(error) {
                   console.log('Could not find entry using access token, Error', error);
                   /// just get out of here
                  return callback({"message": "Entry not found"});
              }).then(function(response) {
                  if(response){
                      // good response
                      return callback(null, data);
                  }else{
                      // bad response
                      return callback({"id": entryId, "message": "Entry not found"});
                  }
              });
    });

    if(entryIds && entryIds.length > 0){
        async.map(entryIds, fn, function(err, results){
            if(err) {
                // deal with the errors
            }
            // your array
            console.log(results);
        });
    }

});
samura
  • 4,375
  • 1
  • 19
  • 26
1

getEntriesBySpace cannot return an array of the items you want (asyncronicity). It can, however, return a promise that references an array of the desired items. Or, since you want errors too, an object that contains both the good results and the errors.

$scope.getEntriesBySpace = function(space, entryIds){

    if(entryIds instanceof Array){
        return Promise.all(entryIds.map(function(entryId){
            return space.cf_space.getEntry(entryId.trim()).catch(function(error) {
                console.log('Could not find entry using access token, Error', error);
                throw error;
            });
       })).then(function(responses) {
           var resultAndErrors = {result: [], errors: []};
           responses.forEach(function(response) {
               if (!response) {
                   resultAndErrors.errors.push(({"id": entryId, "message": "Entry not found"});
               }
               else {
                   resultAndErrors.result.push(response);
               }
           });
           return resultAndErrors;
       });
    }
    else {
        return Promise.resolve([]);
    }
};
Katana314
  • 8,429
  • 2
  • 28
  • 36
1

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) })

trodrigues
  • 1,428
  • 1
  • 9
  • 7