Z
Z
zlodiak2020-11-11 22:09:39
Asynchronous programming
zlodiak, 2020-11-11 22:09:39

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));
                }
                
            }
        });
    }
}


Please help me understand why this is happening. Here is my successful attempt to solve the problem, but this attempt is too verbose. Wish it was simpler and shorter

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

1 answer(s)
A
Aetae, 2020-11-11
@zlodiak

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));
        }

      }
    };
  }
}

PS The second option, by the way, is very bad for you: forEachit 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 question

Ask a Question

731 491 924 answers to any question