4imble
4imble

Reputation: 14416

Convenience method for getting the values out of an array of promises in Bluebird

I have the following code

value1: string;
value2: string;
...
activate(): Promise<any> {
    return Promise.all([
        this.promise1().then(value1 => this.value1 = value1),
        this.promise2().then(value2 => this.value2 = value2)
    ]);
}

Is there a convenience method for something like this?

I tried the following but did not work as I had hoped

return Promise.all([
    this.value1 = this.promise1().value(),
    this.value2 = this.promise2().value()
]);

Upvotes: 0

Views: 42

Answers (2)

Jaromanda X
Jaromanda X

Reputation: 1

There may already be such a convenience method in bluebird, not sure, but I wrote my own that seems to do what you want

const objectPromise = obj => {
    const keys = Object.keys(obj);
    return Promise.all(Object.values(obj)).then(results => Object.assign({}, ...results.map((result, index) => ({[keys[index]]: result}))));
};

To use it

value1: string;
value2: string;
...
activate(): Promise<any> {
    return objectPromise({value1: this.promise1, value2: this.promise2()})
    .then(results => Object.assign(this, results));
}

On searching Bluebird documentation, I came across Promsie.props

So

value1: string;
value2: string;
...
activate(): Promise<any> {
    return Promise.props({value1: this.promise1, value2: this.promise2()})
    .then(results => Object.assign(this, results));
}

should do what you want

Upvotes: 0

alexmac
alexmac

Reputation: 19607

Use single then callback and destructuring assignment syntax, and initialize value1, value2 there:

activate(): Promise<any> {
    return Promise
      .all([
        this.promise1(),
        this.promise2()
      ])
      .then([value1, value2] => {
        this.value1 = value1;
        this.value2 = value2;
      });
}

Upvotes: 1

Related Questions