Web app does not run code in order

Hi @geoffp,

The reason why the id variable is not assigned a value the first time you run the query is because the uuid.v4() function is asynchronous. This means that it does not return the UUID immediately, but instead returns a promise that resolves to the UUID once it is generated.

The first time you run the query, the submit() function is called before the uuid.v4() promise has resolved. This means that the id variable is still undefined when the submit() function is called.

The second time you run the query, the uuid.v4() promise has already resolved, so the id variable has a value when the submit() function is called.

To fix this problem, you need to wait for the uuid.v4() promise to resolve before calling the submit() function. You can do this using the async and await keywords.

Here is a modified version of your code that uses async and await to wait for the uuid.v4() promise to resolve before calling the submit() function:

async function submit() {
  const id = await uuid.v4();

  try {
    NEW_EXPENSE_CLAIM_ID.setValue(id);
    submitNewExpenseClaim.trigger({ 
      additionalScope: { id, data: prepareNewExpenseClaim.value },
    });
  } catch (error) {
    utils.showNotification({title: "Error", description: error, notificationType: "error"});
  }  
}

return submit();

This code will ensure that the id variable has a value before the submit() function is called, so the query will work correctly the first time you run it.

Another option is to use the .then() method on the uuid.v4() promise to call the submit() function once the promise has resolved. Here is an example:

uuid.v4().then((id) => {
  submit(id);
});

This code will also work correctly the first time you run it.

I hope this helps!

:grinning:

Patrick

2 Likes