I have this code for managing dashboard which contains approximate 100 of independent checks.
Check results are received via AJAX call.
There is one initial request for each check at start. After result is received for particular check, the code recursively waits for set timeout and repeats the request again for that check again.
One promise = one check.
I am wondering why promises starts to resolve only after each one of them is pending (none of them is in timeout period). And that is even if response from server is "instantaneous", they just wait for the last promise in cycle.
const TIMEOUT = 4000;
function checkForUpdate(environment, application, check) {
Dashboard.setCheckPending(environment, application, check);
return Communicator.getStatus(environment, application, check)
.then(status => {
Dashboard.updateCheckCell(environment, application, check, status);
Dashboard.updateEnvironmentCell(environment, application);
setTimeout(() => {
return checkForUpdate(environment, application, check)
},
TIMEOUT
);
});
}
Communicator.getEnvMatrix()
.then(data => {
Dashboard.create(data);
$.each(data, (environment, applications) => {
$.each(applications, (application, checks) => {
$.each(checks, (key, check) => {
checkForUpdate(environment, application, check);
});
});
});
});
The question is also how to rewrite that so each of the checks waits just for its own result to be delivered and for set timeout.
EDIT (clarification):
Each of the 100 checks are independent, that is why I want to run AJAX for each of them as soon as I can (inside the $.each()
loops).
The check is dependent only on itself. I don't want it to wait on any other check.
After the result of a check is received it has to wait for set timeout before it tries to retrieve its status again. That is why I encapsulated the recursive function within the setTimeout()
.
Even if I rewrite (see below) the setTimeout()
as promise, the behavior stays the same unfortunately.
function delay(timeout) {
return new Promise(resolve => {
setTimeout(resolve, timeout);
});
}
function checkForUpdate(environment, application, check) {
Dashboard.setCheckPending(environment, application, check);
let promise = Communicator.getStatus(environment, application, check).promise();
return promise
.then(status => {
Dashboard.updateCheckCell(environment, application, check, status);
Dashboard.updateEnvironmentCell(environment, application);
return delay(TIMEOUT).then(() => {
return checkForUpdate(environment, application, check);
});
});
}