简体   繁体   English

JavaScript读取数组中的对象

[英]JavaScript reading objects in array

Yesterday one of the members here on StackOverflow helped me with AJAX calls but now i have a problem. 昨天,StackOverflow上的一位成员帮助我进行了AJAX调用,但现在我遇到了问题。

Code is actually a loop that sends requests to multiple REST APIs and save results in array as objects. 代码实际上是一个将请求发送到多个REST API并将对象中的结果保存在数组中的循环。

Now the problem is that i cannot read objects from that array. 现在的问题是我无法从该数组读取对象。

I would like to read objects and write new objects or update existing objects in that array. 我想读取对象并编写新对象或更新该数组中的现有对象。

Code: 码:

$(document).ready(function() {
var items = [];
var types = [{
        suffix: '_ONOFF',
        handler: function(data, $el) {
            $el.prop('checked', data == 'ON');
        }
    },
    {
        suffix: '_URA',
        handler: function(data, $el) {
            $el.val(data);
        }
    },
    {
        suffix: '_MINUTA',
        handler: function(data, $el) {
            $el.val(data);
        }
    },
    {
        suffix: '_PO',
        handler: function(data, $el) {
            if (data == "ON") {
                $el.css('background', 'blue');
            } else if (data == "OFF") {
                $el.css('background', 'black');
            }
        }
    },
    {
        suffix: '_TO',
        handler: function(data, $el) {
            if (data == "ON") {
                $el.css('background', 'blue');
            } else {
                $el.css('background', 'black');
            }
        }
    },
    {
        suffix: '_SR',
        handler: function(data, $el) {
            if (data == "ON") {
                $el.css('background', 'blue');
            } else {
                $el.css('background', 'black');
            }
        }
    },
    {
        suffix: '_CE',
        handler: function(data, $el) {
            if (data == "ON") {
                $el.css('background', 'blue');
            } else {
                $el.css('background', 'black');
            }
        }
    },
    {
        suffix: '_PE',
        handler: function(data, $el) {
            if (data == "ON") {
                $el.css('background', 'blue');
            } else {
                $el.css('background', 'black');
            }
        }
    },
    {
        suffix: '_SO',
        handler: function(data, $el) {
            if (data == "ON") {
                $el.css('background', 'blue');
            } else {
                $el.css('background', 'black');
            }
        }
    },
    {
        suffix: '_NE',
        handler: function(data, $el) {
            if (data == "ON") {
                $el.css('background', 'blue');
            } else {
                $el.css('background', 'black');
            }
        }
    },
    {
        suffix: '_VALVE_SET',
        handler: function(data, $el) {
            $el.text(data);
        }
    },
];

for (var r = 1; r < 11; r++) {
    var result = {};
    types.forEach(function(type) {
        var key = `HVAC_VALVE01_SCHED${r}${type.suffix}`;
        $.ajax({
            type: "GET",
            url: `http://192.168.1.111:8080/rest/items/${key}/state`
        }).done(function(data) {
            type.handler(data, $('.' + key));
            result[key] = data;
        });
    });
    items.push(result);
}
console.log(items);
console.log(items['HVAC_VALVE01_SCHED1_ONOFF']);
});

You see nothing in your console.log s because every AJAX call is asynchronous , and your code after the loop executes before the result of API call will be received. 您不会在console.log看到任何内容,因为每个AJAX调用都是异步的 ,并且循环执行之后的代码将在收到API调用的结果之前执行。 When I deal with multiple asynchronous operations, which you want to do at the same time, I usually use Promise.all , and I really love it. 当我要同时处理多个异步操作时,通常使用Promise.all ,我真的很喜欢它。 Promise.all accepts an array of promises and you can handle response inside then and catch blocks as with regular single promise. Promise.all接受承诺的数组,你可以处理内部响应thencatch块与普通单一的承诺。 But notice, that Promise.all accepts an array, and in then block you will get an array too, an array of responses. 但是请注意,这Promise.all接受一个数组,并在then阻止你将得到一个数组也响应数组。

var apiCalls = [];
for (var r = 1; r < 11; r++) {
    var result = {};
    types.forEach(function(type) {
        var key = `HVAC_VALVE01_SCHED${r}${type.suffix}`;
        apiCalls.push(
            $.ajax({
                type: "GET",
                url: `http://192.168.1.111:8080/rest/items/${key}/state`
            })
        )
    });
}
Promise.all(apiCalls)
    .then(function(response) {
        // "response" will contain the results of ALL you AJAX calls from "apiCalls" array
        // "response" will be an array of responses, so you have to merge this response with "items" array by yourself
        console.log(response); // here you can do all operations like "push" to existing array and so on
    })
    .catch(function(err) {
        console.error(err);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM