我有以下代码
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()
]);
答案 0 :(得分:1)
使用单then
个回调和解构分配语法,并在那里初始化value1
,value2
:
activate(): Promise<any> {
return Promise
.all([
this.promise1(),
this.promise2()
])
.then([value1, value2] => {
this.value1 = value1;
this.value2 = value2;
});
}
答案 1 :(得分:0)
蓝鸟可能已经有这样一种方便的方法了,不确定,但是我写了自己似乎做你想做的事情
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));
}
在搜索 Bluebird 文档上,我遇到了Promsie.props
所以
value1: string;
value2: string;
...
activate(): Promise<any> {
return Promise.props({value1: this.promise1, value2: this.promise2()})
.then(results => Object.assign(this, results));
}
应该做你想做的事情