链接随后的承诺并等待所有人解决 [英] Chaining subsequent promises and wait for all to resolve

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

问题描述

我已经阅读了一些关于诺言的文章和问题,但是我仍然难以理解.这是我想做的:

I have already read some articles and questions about promises but I still have problems to get my head around them. Here's what I want to do:

我的应用程序应从设备请求属性.这些属性可以表示为单个值或数组.每个属性都有属性,这些属性可以为我提供有关它的信息(例如它是数组,可写等).

My application should request properties from a device. The properties can be represented as single value or as an Array. Every property has attributes, that give me information about it (like is it an array, is it writeable, etc.).

因此,我的第一个尝试是首先读取属性的属性.因此,我可以查看是否需要读取一个值或一个数组(例如).

So my first attempt was to read the attributes of an property first. So I can see if I need to read a single value or an Array (for example).

一切都与websockets一起使用,所以我没有使用angulars $ http服务.

Everything is working with websockets, so I'm not using angulars $http service.

var valueRequests = [];

angular.forEach(properties, function (property, key) {

    requestPropertyAttributes(property).then(function (result) {

        if (result.isList) {

            valueRequests.push(requestPropertyList(property));
        }
        else {

            valueRequests.push(requestPropertyValue(property));
        }
    });
});

$q.all(valueRequests).then(function () {

    //do sth. after all data was read
});

好吧,我所得到的只是一些错误(它读取列表中的值,和/或反之亦然),并且$ q.all()不会触发.

Well, all I got with this are some errors (it reads list where are values and/or vice versa) and $q.all() does not fire.

我的请求函数正在返回承诺.

My request Functions are returning promises.

这是正确的尝试还是我在某个地方失败了?就像我说的那样,我对诺言并不十分确定,因此我可能对这里的机制有所了解.

Is this the correct attempt or have I failed somewhere? As said I'm not really sure with promises, so I may have a problem of understanding the mechanism here.

感谢您的帮助:)

推荐答案

您需要返回第一个then内部的内部诺言,然后将该诺言添加到列表中.

You need to do a return of the inner promise inside the first then, and then add that promise to the list.

var valueRequests = [];

angular.forEach(properties, function (property, key) {

    valueRequests.push(requestPropertyAttributes(property).then(function (result) {

        if (result.isList) {

            return requestPropertyList(property);
        }
        else {

            return requestPropertyValue(property);
        }
    }));
});

$q.all(valueRequests).then(function () {

    //do sth. after all data was read
});

这篇关于链接随后的承诺并等待所有人解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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