I want to write in Javascript the following pseudo-code:
function asyncOperation() {
return new Promise((resolve, reject) => {
....
}
}
while (true) {
result = asyncOperation()
if result is good then break the loop;
else loop again
}
I'll explain it in words: asyncOperation uses a Promise, for example an AJAX call. I want that if the promise is rejected, then asyncOperation will be invoked again. Do you know how it can be done in Javascript?
If you're going to use a loop, then you will have to use await
because otherwise, your loop will just run forever and never give the asynchronous operation any cycles to actually process its completion:
while (true) {
result = await asyncOperation()
if (good result) {
break;
}
}
This, of course, needs to be inside a function declared as async
.
Before await
, the usual way to do this would be with a local function and a recursive-looking structure (that by the way does not have any stack build-up from recursion because of the async operation):
function run() {
return asyncOperation().then(result => {
if (good result) {
return result;
} else {
// try again
return run();
}
});
}
run().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
And, typically you would insert some small delay before calling the asyncOperation()
again in order to avoid hammering the target server. And, you would have either a timeout or a max number of retries to avoid a situation where this loop runs forever.
Wouldn't something like this just be sufficient:
async function loopUntilTrue() {
let success = false;
while (!success) {
try {
await asyncOperation();
success = true;
} catch {
success = false;
}
}
}
I created a loop function to do that
let count = 0;
function asyncOperation() {
return new Promise((resolve, reject) => {
if (count < 10) {
console.log('reject', count++);
reject();
return;
}
resolve(console.log('resolve', count));
});
}
async function loop() {
while (true) {
try {
await asyncOperation();
break;
} catch {
continue;
}
}
}
loop();
The result is this:
reject 0
reject 1
reject 2
reject 3
reject 4
reject 5
reject 6
reject 7
reject 8
reject 9
resolve 10
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.