Skip to content Skip to sidebar Skip to footer

How To Retrieve The Key/value Object In Json With Javascript?

I have a weird problem. First I retrieve several calls at the same time. And save the returned data in a variable called 'values' function PrefsService($resource,PrefsResource,$q

Solution 1:

This syntax looks weird:

return {
    values
}

Its basically an object literal with a property name, but no value. In any case what you are tagging on to the initial all is unnecessary:

.then(function(values) {

      return {
        values
      }
    })

Just remove that part.

Solution 2:

The returned values are promises, use them as promises like you are supposed to:

PrefsService
.initialize()
.then(function(values) {
    values.map(function(valuePromise) {
       valuePromise.then(function(value) {
           console.log(value);
       });
    });
 });

Solution 3:

The most straightforward way would be to return the actual values, not the promises:

functionPrefsService($resource,PrefsResource,$q) {

    var initialize = function() {

      return$q
        .all([
          PrefsResource.get({key:"TwentyFourHourTime"}),
          PrefsResource.get({key:"DecimalTime"}),
          PrefsResource.get({key:"startDayOfWeek"}),
          PrefsResource.get({key:"RoundingIncrement"}),
          PrefsResource.get({key:"RoundingOption"})
        ])
        .then(function(values) {
          var returnValues = [];
          values.forEach(function(v) { 
              v.then(function(a) { 
                  returnValues.push(a); 
              })
          });
          return returnValues;
        })
    };

    return {
        initialize:initalize;
    }
}


PrefsService
   .initialize()
   .then(function(values) {
      console.log(values); //an array of the actual values, not the promises
   })

Post a Comment for "How To Retrieve The Key/value Object In Json With Javascript?"