I encountered unexpected behavior in the execution sequence of my code. Here is the code snippet:
console.log("1"); await reloadScenarios(); console.log("2"); const reloadScenarios = () => { if (token) { getScenario() .then(({ scenarios }) => { console.log("3"); const transformedScenarios = scenarios.map(option => ({ scenario: option.name, description: option.categories.name, value: option._id })); setOptions(transformedScenarios); // setSelectedOption(transformedScenarios[0]?.value || null); }) .catch((error) => { console.error('Failed to fetch scenario options:', error); }); } };
I expect the execution order to be 1,3,2. However, when I run the code, the actual order is 1,2,3. Can someone explain why this is happening?
Additionally, I noticed that when I modified the reloadScenarios function to include a return statement before getScenario(), the execution order changed to 1, 3, 2 - which is the desired order. Do I really need a return statement, or is there some other explanation to achieve the desired sequence?
Your problem is that you are using await to call a function that is not asynchronous and does not return a Promise. Since the function does not return a Promise, execution continues.
If you want the displayed sequence to be "1,3 2" then you must mark your function with
async
This way, when you mark
await reloadScenarios
, you are waiting for the promise to be resolved (or rejected).For more details, see the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
edit Sorry, I forgot, one more problem: you also have to return the promise in the function