0

I have this submit function that runs two functions when clicked on.
My issue is that props.updateValues() is executed before createAffiliation(values)

How can I change the order of the execution?

const onSubmit = () => { 
  createAffiliation(values)
  props.updateValues();
}

createAffiliation:

export function createAffiliation(anknytning: Anknytning) {
  return axios
    .post(Endpoints.affiliationData, anknytning)
    .then((response: AxiosResponse<any>) => {
      console.table("Created affiliation", anknytning);
      return Promise.resolve(response.data);
    })
    .catch(reason => {
      console.error("Could not create affiliation", reason);
      return Promise.reject(reason);
    });
}
SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
Arasto
  • 471
  • 6
  • 25
  • Is `createAffiliation` an async method? Can you show the implementation of createAffiliation and updateValues method? – Nikhil Goyal Jan 22 '20 at 13:32
  • I'm guessing the 'createAffiliation' is an async method, so you'll need a call back to handle it, or a promise. – Kyle Jan 22 '20 at 13:33
  • Make both functions synchronous or use `async ... await` or `Promises` – empiric Jan 22 '20 at 13:33
  • Does this answer your question? [Is there a way to wait until a function is finished?](https://stackoverflow.com/questions/54429091/is-there-a-way-to-wait-until-a-function-is-finished) – lehm.ro Jan 22 '20 at 13:39

2 Answers2

1

This happens because createAffiliation function returns a promise so we don't know when it will be resolved or rejected. Javascript will continue to execute your code, so props.updateValues() executes first.

There are 2 common way to resolve this issue.

1-) async await:

An async function can contain an await expression that pauses the execution of the async function to wait for the passed Promise's resolution, then resumes the async function's execution and evaluates as the resolved value.

The purpose of async/await is to simplify using promises synchronously. It can only be used inside an async function.

const onSubmit =  async () => { 
  try {
    await createAffiliation(values)
    props.updateValues();
  } catch (err) {
    console.log(err);
  }
}

2-) with then catch block you can do like this:

const onSubmit = () => {
  createAffiliation(values)
    .then(() => props.updateValues())
    .catch(err => console.log(err));
};
SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
1

As first function is returning a promise you can use .then() to let the first one finish:

const onSubmit = () => { 
  createAffiliation(values)
  .then(()=>props.updateValues());
}

Or if you would like to see about Promise.race().

Jai
  • 74,255
  • 12
  • 74
  • 103