[英]JavaScript reading objects in array
昨天,StackOverflow上的一位成員幫助我進行了AJAX調用,但現在我遇到了問題。
代碼實際上是一個將請求發送到多個REST API並將對象中的結果保存在數組中的循環。
現在的問題是我無法從該數組讀取對象。
我想讀取對象並編寫新對象或更新該數組中的現有對象。
碼:
$(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']);
});
您不會在console.log
看到任何內容,因為每個AJAX調用都是異步的 ,並且循環執行之后的代碼將在收到API調用的結果之前執行。 當我要同時處理多個異步操作時,通常使用Promise.all
,我真的很喜歡它。 Promise.all
接受承諾的數組,你可以處理內部響應then
與catch
塊與普通單一的承諾。 但是請注意,這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.