mpint
mpint

Reputation: 498

Is it possible to assign a resolved promise to a property of an object?

I'm playing around with promises here and trying to assign a pair of resolved promises as properties of an object by wrapping each promise in an IIFE. However, the resolved promises are never assigned, although they are definitely pulling down the requested data.

It would be great if I could get this to work since it's more terse and expressive than success/then/error/catch blocks. Is it possible to use promises this way?

var obj = function() {   
    return new Promise(function(resolve, reject){
      return {
          primary: function() {
              return this.promisifiedHttpRequest(primaryQuery, options);
          }.call(this),
          secondary: function() {
              return this.promisifiedHttpRequest(secondaryQuery, options);
          }.call(this)
      }
  }.bind(this));
}

The expected result is as follows:

var obj = {
    primary: primaryQueryResponse,
    secondary: secondaryQueryResponse
};

Upvotes: 4

Views: 3732

Answers (1)

Katana314
Katana314

Reputation: 8620

As JLRishe said, it's a little hard to interpret exact intentions with that code. I think this is what you're looking for. This will give back a promise with an array-result.

return Promise.all([this.promisifiedHttpRequest(primaryQuery, options),
this.promisifiedHttpRequest(secondaryQuery, options)]);

Or, if you liked having a "{primary: ..., secondary: ...}" object, try this:

    return Promise.all([this.promisifiedHttpRequest(primaryQuery, options),
this.promisifiedHttpRequest(secondaryQuery, options)]).then(function(resultArr) {
  return {
    primary: resultArr[0],
    secondary: resultArr[1]
  }
});

It took me a while to learn this, and perhaps it's not something to abuse, but the return value of .then() is very useful for "converting" a promise to something else.

Upvotes: 2

Related Questions