Inconsistent with the execution order of await statements
P粉691461301
P粉691461301 2023-09-12 13:42:02
0
1
636

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粉691461301
P粉691461301

reply all(1)
P粉019353247

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template