等待多方面的承诺 [英] Awaiting mulitple promises

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

问题描述

我需要等待多个诺言的完成.并行执行它们,然后在它们全部完成后执行另一个功能的最佳方法是什么?根据下面的示例,我可以使用getAddress1.then()来做某事 一旦返回了Address1的值,但我将等待几个诺言(Address1,Address2等).您如何等待它们全部完成,然后使用所有可用数据启动下一个功能?我尝试了$ .when(),但它 似乎没有用.它返回的是承诺对象,而不是我所希望的已兑现承诺的值.

I need to await the completion of multiple promises.  What is the best way to execute them in parallel and then execute another function once they are all complete?  Based on the example below, I can use getAddress1.then() to do something once the Address1 value is returned, but I will be awaiting several promises (Address1, Address2, etc.).  How do you wait until they are all complete, then fire the next function with all of the data available?  I tried $.when() but it doesn't seem to be working.  It returns a promise object not the value of the fulfilled promise as I had hoped.

for (var i = 0; i < locations.data.length; i++) {
            var location = locations.data[i];

            var address1 = location.getAddress1().then(function (value) {
                console.log(value); // this is the value I want
            });
         
            console.log(address1); // this is the promise object

            $.when(address1).then(function (value) {
                console.log(value); // this is the promise object
            });


        }

推荐答案

Hessc,

Hi Hessc,

我在对以下堆栈溢出帖子的回答中涵盖了应允情况,该帖子应该有所帮助:-

I covered a promise situation in my answer to the following stack overflow post which should help: -

Lightswitch html如何知道何时进行异步迭代

本质上,解决方案是创建一个要处理的承诺数组,然后加入并执行它们.

Essentially the solution is to create an array of the promises to be processed and then join and execute them.

HTH,

克里斯


这篇关于等待多方面的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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