如何等待诺言在地图内解决? [英] How to wait for a promise to resolve inside a map?

查看:43
本文介绍了如何等待诺言在地图内解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要处理的对象列表.该对象被传递到一个promise函数,该函数将执行此操作并进行解析.根据先前缓存的值,该过程可能是即时的,也可能不是即时的.如果已经有计算值,它将立即解决.否则,它将进行计算.现在我遇到的问题是,在计算第一个对象的状态之前,将下一个对象传递给Promise:

I have a list of objects that I want to process. The object is passed to a promise function that does this and that and resolves back. The process could be instant or not, based on previously cached value. If there is already calculated value, it will resolve to it instantly. Else, it will calculate. Now the issue I am having is that the next object is passed to the promise before the first object's status is calcualted:

   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}

      ];

现在,即使在某个实例上需要花费一分钟的时间来计算,我现在也要绝对等待该承诺在循环期间解决.同一组中的所有人都具有相同的状态.因此,promise检查是否已经计算了一个组.如果是,则将其返回.否则,它进行计算.这就是问题所在.在杰西卡1完成之前,其他人已通过.

now I want to absolutely wait for the promise to resolve during loop even if the promise takes a minute to calculate on the very instance. All people with the same group have the same status. Hence, the promise checks if a group has already been calculated. If yes, returns it. Else, it calculates. and that's where the issue lies. Before Jessica 1 is finished, the other people are passed.

    people.map(function(person) {
   // return the promise to array
   this.calculatorService
    .getStatus(person)
    .then(function(res) {
      person.status = res;


    });
});

推荐答案

数组迭代器(例如 map forEach )不适用于promises,因为它们不知道如何等待结果.使用简单的 for 循环:

Array iterators like map or forEach don't work with promises because they don't know how to await a result. Use a simple for loop instead:

for (let person of people)
  person.status = await this.calculatorService.getStatus(person)

如果您确实想要功能性"方式(并避免显式异步/等待),则可以定义类似于bluebird的

If you really want a "functional" way (and avoid explicit async/await), you can define a function similar to the bluebird's Promise.each:

Promise.each = function(ary, fn) {
    return ary.reduce((p, x) => p.then(() => fn(x)), Promise.resolve(null))
}

并像这样应用它:

function setStatus(person) {
    return calculatorService
        .getStatus(person)
        .then(res => person.status = res);
}

Promise.each(people, setStatus).then(...)

这篇关于如何等待诺言在地图内解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆