I saw a few issues related to Promises repetition, however, what I want to do is slightly different in that I would like to control the retry / rejection of promises conditionally until the max reps are reached.
To give a simple example, imagine that we are assuring a promise around XMLHttpRequest. When a request loads with status ...
200: resolve promise299: try again immediately399: cancel immediately499: get something from the server, and then try again
Note that there is scope for asynchronous behavior that must be performed before repeating.
The solution I reviewed includes two Promises.
- Firstly, it is a wrapper around each attempt and makes a simple decision / rejection based on the result of this attempt.
- Secondly, it is a shell around many attempts, which conditionally discards individual promises.
Going back to the example I mentioned ...
- The first promise rules everyone
XMLHttpRequest, resolving a condition 200and refusing otherwise. - The second promise resolves itself when any attempt is permitted. Whenever an attempt is rejected, it makes a decision about the next action (retry, reject, retrieve, retry, etc.) Based on this attempt status code.
I think that with this I will go in the right direction, but I canβt find a concrete solution. I am looking to create a common wrapper for this kind of "shareware promises."
Edit:
Here is the solution:
async function tryAtMost(maxAttempts, asyncCall, handleError)
{
for (let i = 0; i < maxAttempts; i++)
{
try
{
return await asyncCall();
}
catch (error)
{
const nextAction = await handleError(error);
const actionError = new Error(nextAction.error);
switch (nextAction.type)
{
case ACTIONS.ABORT:
throw actionError;
case ACTIONS.RETRY:
if (i === maxAttempts - 1) { throw actionError; }
else { continue; }
}
}
}
}