代码之家  ›  专栏  ›  技术社区  ›  4imble

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

  •  0
  • 4imble  · 技术社区  · 7 年前

    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()
    ]);
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   alexmac    7 年前

    使用单个 then 回调和 分解分配 value1 value2 有:

    activate(): Promise<any> {
        return Promise
          .all([
            this.promise1(),
            this.promise2()
          ])
          .then([value1, value2] => {
            this.value1 = value1;
            this.value2 = value2;
          });
    }
    
        2
  •  0
  •   Jaromanda X    7 年前

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

    在…上 搜索 蓝知更鸟 文档 ,我偶然发现 Promsie.props

    所以

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

    应该做你想做的事