Wed*_*ada 12 javascript typescript angular
我有一个要处理的对象列表。该对象被传递给一个承诺函数,该函数执行此操作并解析返回。根据先前缓存的值,该过程可能是即时的,也可能不是。如果已经有计算值,它会立即解析到它。否则,它会计算。现在我遇到的问题是在计算第一个对象的状态之前将下一个对象传递给承诺:
let people = [
{groupId: 1, name: 'Jessica Coleman', status: 'Unknown', id:1}
{groupId: 1, name: 'Eric Tomson', status: 'Unknown', id:2}
{groupId: 1, name: 'Samuel Bell', status: 'Unknown', id:3}
];
Run Code Online (Sandbox Code Playgroud)
现在我想绝对等待承诺在循环期间解决,即使承诺需要一分钟来计算实例。同一组中的所有人员都具有相同的状态。因此,promise 检查是否已经计算了一个组。如果是,则返回它。否则,它会计算。这就是问题所在。杰西卡1号还没说完,其他人就通过了。
people.map(function(person) {
// return the promise to array
this.calculatorService
.getStatus(person)
.then(function(res) {
person.status = res;
});
});
Run Code Online (Sandbox Code Playgroud)
geo*_*org 18
数组迭代器喜欢map或forEach不喜欢Promise,因为它们不知道如何等待结果。改用一个简单的for循环:
for (let person of people)
person.status = await this.calculatorService.getStatus(person)
Run Code Online (Sandbox Code Playgroud)
如果你真的想要一种“功能性”的方式(并避免显式的 async/await),你可以定义一个类似于 bluebird 的函数Promise.each:
Promise.each = function(ary, fn) {
return ary.reduce((p, x) => p.then(() => fn(x)), Promise.resolve(null))
}
Run Code Online (Sandbox Code Playgroud)
并像这样应用它:
function setStatus(person) {
return calculatorService
.getStatus(person)
.then(res => person.status = res);
}
Promise.each(people, setStatus).then(...)
Run Code Online (Sandbox Code Playgroud)
使其与 同步工作async/await。(顺便说一句,比这种情况for..of更适合)。.map
for (let person of people) {
person.status = await this.calculatorService.getStatus(person);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5972 次 |
| 最近记录: |