Answer the question
In order to leave comments, you need to log in
How to make setTimeout call and recursion asynchronous?
Colleagues, please help.
There are several requests to the server. In return, the server creates tasks for these requests and gives the task id, by which I check the status of the task with another request.
When all tasks are completed, the execution of the synchronous code must continue.
How to wait for all tasks to complete?
Here's how it's set up for me:
async getTaskStatus(id, resolve) {
if (!this.queryCounter) {
this.queryCounter = 0;
}
if (this.queryCounter > 20) {
return this.errHandler();
}
try {
const { data: { data: { status } } } = await checkTaskStatus(id);
if (status === 'done') {
return resolve();
} if (status === 'error') {
this.$message.error('Ошибка проведения операции, попробуйте позже');
this.$router.push('/users');
} else {
setTimeout( () => {
this.queryCounter++;
this.getTaskStatus(id, resolve);
}, 500);
}
} catch (e) {
console.error(e);
}
};
try {
const { id } = this.ruleForm.user_dto;
const tasks = [];
tasks.push(updateUserData(id));
tasks.push(updateATTRData(id));
tasks.push(updateOldATTRData(id));
const results = await Promise.all(tasks);
for (let i = 0; i < results.length; i++) {
if (results[i].data.validation_result.success === true) {
let resolve = () => Promise.resolve();
await this.getTaskStatus(results[i].data.data, resolve);
} else {
this.errHandler();
}
}
this.setUser(this.userId);
this.editAdmin = false;
} catch (e) {
this.errHandler();
console.error(e);
}
Answer the question
In order to leave comments, you need to log in
Wrap everything in an anonymous async, and then two Promise.all. The bottom line is that you have to "bring" your synchronous code into the asynchronous "then" via await or Promise - it doesn't matter.
This is how the design should look like
(async () => {
let reqs = [];
async function doTasks() {
return Promise.all( reqs.map((req) => doReq(req)) )
.then((tasks) => Promise.all( tasks.map((task) => checkStatus(task)) ))
.catch(console.error);
};
await doTasks();
// do some sync code
})();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question