Answer the question
In order to leave comments, you need to log in
How to call nested async functions?
I'm trying to call other async functions inside an async function, but I'm getting the following error message:
Can not use keyword 'await' outside an async function
Here's the code:
export const setGenderThunk = (gender, login) => {
return async dispatch => {
const users = await getUsers || []; // там внутри fetch
users.forEach(user => {
if(user.login === login) {
const user_ = { ...user, gender: gender };
await setUser(user_, user.id); // там тоже внутри fetch
debugger
if(result.ok) {
dispatch(setGenderAC(user_.gender));
}
}
});
}
}
export const setGenderThunk = (gender, login) => {
return async dispatch => {
const users = await getUsers || [];
users.forEach(user => {
if(user.login === login) {
const user_ = { ...user, gender: gender };
;(async () => {
const result = await setUserF(user_, user.id);
debugger
if(result.ok) {
dispatch(setGenderAC(user_.gender));
}
})();
}
});
}
}
async function setUserF(user, id) {
return await setUser(user, id);
}
Answer the question
In order to leave comments, you need to log in
forEach
- synchronous. Either use either those who know how to async forEach, or use regular loops:
export const setGenderThunk = (gender, login) => {
return async dispatch => {
const users = await getUsers || []; // там внутри fetch
for(let user of users) {
if(user.login === login) {
const user_ = { ...user, gender: gender };
await setUser(user_, user.id); // там тоже внутри fetch
debugger
if(result.ok) {
dispatch(setGenderAC(user_.gender));
}
}
};
}
}
forEach
it still works synchronously, but at the same time it produces a lot of asynchronous functions that run in parallel (which, of course, no one expects).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question