Handling an array of input data with asynchronous calls for each element can be tricky, especially when trying to avoid hitting rate limits on a server. While underscore _.delay()
can help with the processing, there are still a few challenges to address. How can we (a) cancel delayed execution if the user decides to stop, and (b) display status updates that include the current index of the array?
Here's the current code snippet...
function processArray(array) {
var processElement = function(element) {
return doAsyncTask(element); // asynchronous task returning a promise
};
_.each(array, function(element, index) {
_.delay(processElement, index * 1000, element);
});
}
function userDecidesToCancel() {
// need help here
}
In case a user cancels the process before element N, it's acceptable to let doAsyncTask(N-1)
finish, but we shouldn't initiate work for any elements beyond that point (for N >= 1). Is there a way to achieve this?
When it comes to status updates, it's challenging to display progress elegantly. Ideally, we'd like to indicate when each item is completed out of the total, as shown in the following example...
_.each(array, function(element, index) {
_.delay(processElement, index * 1000, element).then(function(result) {
// how to retrieve and log the result here for status update?
console.log("Finished processing item " + index + " with result: " + result);
});
});
While part of the log message can be included in the processElement
function (for logging the result), the index relative to the array length is crucial for displaying progress percentage. This index information should be handled within the _.each
loop itself, rather than passing it to the processElement
function.
Any assistance on these matters would be greatly appreciated. Thank you.