简体   繁体   中英

JavaScript reading objects in array

Yesterday one of the members here on StackOverflow helped me with AJAX calls but now i have a problem.

Code is actually a loop that sends requests to multiple REST APIs and save results in array as objects.

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. 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 accepts an array of promises and you can handle response inside then and catch blocks as with regular single promise. But notice, that Promise.all accepts an array, and in then block you will get an array too, an array of responses.

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);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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