search

Home  >  Q&A  >  body text

Inconsistent with the execution order of await statements

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?

P粉691461301P粉691461301444 days ago641

reply all(1)I'll reply

  • P粉019353247

    P粉0193532472023-09-13 12:18:25

    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

    const reloadScenarios = async () => {
        // Your body function
    };
    

    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

    reply
    0
  • Cancelreply