Reputation: 5261
I'm currently doing some post requests within an interval function:
let getStatusIV = setInterval( () => {
let data = {
action: 'get_products_status',
import_id: importId
};
$.post( ajaxurl, data, function () {
} ).done( response => {
if (response.success && response.data) {
// showLoadingSpinner( '#wpcontent', response.data ); <- Sets the text at an overlay
}
} )
}, 500 );
This interval / post function returns the status of another AJAX call from my backend - for example: Processed 20 of 700 products
The problem is, that the requests are not resolving in the order they were called so as a result I'm getting this example:
Processed 20 of 700 products
Processed 19 of 700 products
Processed 30 of 700 products
Processed 80 of 700 products
Processed 75 of 700 products
Any idea to fix this? I really need short intervals so just settings a longer interval time dont helps.
Upvotes: 0
Views: 65
Reputation: 23
That's how asynchronous programming works. Since you have so much things to be processed, keep calling .then() won't be that practical then. But why is the order so important? In reality most operations are processed asynchronously to maximize efficiency. I'm a newbee by the way, but I did encounter this, I just made everything asynchronous to solve the same problem.
------------------------------------
Okay, now I find a way to accomplish this. This is an example from JavaScript: The Definitive Guide by David Flanagan. You may want to check it out because it's indeed AWESOME.
function fetchSequentially(urls) {
const bodies = [];
//Response bodies are stored here
function fetchOne(url) {
return fetch(url)
.then((response) => response.text())
.then((body) => {
bodies.push(body);
});
}
let p = Promise.resolve(undefined);
//Fulfill an empty promise to initiate the promise chain
for (url of urls) {
p = p.then(() => fetchOne(url));
//Build the promise chain automatically
}
return p.then(() => bodies);
/*
Return bodies. It's a promise so you may call
.then() one last time to get the output.
For the progress bar, you may want to use event
to track how many requests have been done.
*/
}
Actually you can just use event to deal with the progress bar problem to keep the requests "parallel". Just emit an event to announce that one request has done. Listen to the event and track how many instead of which one has finished. Then the progress bar will never go backwards.
Upvotes: 1