0

This is my code:

    function login(event) {
      event.preventDefault();
      console.log("*1*");
      let formData = new FormData(event.target);
      ApiRequest.axiosInstance({ method: "post", url: "/login/login.php", data: formData, headers: {} })
        .then(res => {
            console.log("*2*");
            getUsersProduct;
            console.log("*3*");
        })
        .catch((err) => {
            console.error(err);
            console.log("*4*");
        })
        .then(() => {
            console.log("Login Finished");
            console.log("*5*");
        });
    }
}

function getUsersProduct() {
    console.log("*6*");
    ApiRequest.axiosInstance({ method: "post", url: "/login/getUsersProduct.php", data: formData, headers: { "Content-Type": "multipart/form-data" } })
    .then(res ....
    console.log("*7*");
}

I didnt write down the whole code but my problem is it show me console output: 1 2 6 3 instead of 1 2 6 7 3

the function getUsersProduct has to finish first. How do I do this in my react code? Do I have to use async and await?

hansvdzz
  • 21
  • 2
  • 3
    There's a lot broken here. If you want to wait for `getUsersProduct()` it needs to return a promise, you need to actually call it (right now you're not, it needs `{}`) and you need to return the promise _it_ returns in your callback to `then()`. – Evert Mar 21 '23 at 09:48
  • 1
    Where do you call `getUsersProduct`? I only see a line of `getUsersProduct;`, which is not a call to the function. Also, what should not run before `getUsersProduct`? – Lajos Arpad Mar 21 '23 at 10:13
  • Yes it must be getUsersProduct(); in the first .then(res – hansvdzz Mar 21 '23 at 10:34
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – trincot Mar 21 '23 at 15:36

1 Answers1

0

I found it myself and solved it with async and await:

In the first ApiRequest -> in the then method ->

.then(async res => {

and the keyword await just before the function call ->

data = await getUsersProduct();

In the getUsersProduct function, I created a Promise and also used the async and await ->

function getUsersProduct() { return new Promise(async resolve => { await ApiRequest.axiosInstance ...

This work for me.

hansvdzz
  • 21
  • 2