从 Bluebird 中的承诺数组中获取值的便捷方法

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

我有以下代码

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

有这样的便捷方法吗?

我尝试了以下但没有像我希望的那样工作

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

使用单个 then 回调和 解构赋值 语法,并初始化 value1value2

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

bluebird 中可能已经有这样一个方便的方法,不确定,但我自己写的似乎可以满足您的需求

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

使用它

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

所以

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

应该做你想做的事