2

I have the next functions:

export const getSet = async (
    projectId,
    setId,
    dispatch
) => await (
    projectId && setId &&
    setsDb
    .child(`${projectId}/${setId}`)
    .once("value", async snap => {
        const set = snap.val();

        const elements = Object.keys(set);
        const elementsClasses = await getClassesForElements(projectId, elements);

        const classes = Object.values(elementsClasses);
        const classesAttributes = await getClassesAttributes(projectId, classes);

        dispatch(setClasses(classesAttributes));
        dispatch(setElements(elementsClasses));
        dispatch(setSet(set));
    })
);

export const getPageDetails = (projectId, pageId) => (
    dispatch => (
        projectId && pageId &&
        pagesDb
        .child(`${projectId}/${pageId}`)
        .once("value", async snap => {
            const pageDetails = snap.val();
            const { setId } = pageDetails;

            await getSet(projectId, setId, dispatch)

            dispatch(
                setPageDetails(
                    pageDetails
                )
            );
        })
    )
);

I don't have too much experience in async functions, but what I want to earn is to make getPageDetails wait with dispatch(setPageDetails(pageDetails)) until getSet finishes all the dispatches. In the above functions everything works fine except that getSet finishes latest. How to solve this?

Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64

1 Answers1

1

await is only going to pause things if the expression you are waiting for evaluates to a promise.

once takes a callback, so presumably, it doesn't return a promise.

Therefore you need to wrap it with a function which does return a promise that resolves when once is done (which means converting all the dispatch calls too).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335