I'm trying to do some work in JavaScript - I call an async function from an async function, as shown below.
useEffect(() => {
(async () => {
await asyncFunction();
// do stuff
})();
}, []);
asyncFunction looks like this
const asyncFunction = (dispatch) => {
return async (data) => {
try {
const response = await APICall();
dispatch({ type: "search", payload: response.data });
}
// error handling
}
asyncFunction dispatches to a reducer, which returns return { errorMessage: "", data: action.payload };
With my own testing, I've seen that console.log(asyncFunction())
returns a promise, and console.log(await asyncFunction())
returns nothing.
One weird thing I have noticed is when placing console.log statements in each part of the program, the promise from the function call (in the useEffect block) is printed out first, then the data in the reducer from the console.log statement I added right about return { errorMessage: "", data: action.payload };
.
So my question is, how do I access this data? I've looked at some other threads on here which recommend using .then
, but that was unsuccessful. Is there a way to do it without passing in a callback function (doing so would mean I need to restructure the whole program).
This post is a bit long, so if you have any questions, or need additional parts of my program, please let me know.