Gabriel Linassi
Gabriel Linassi

Reputation: 541

how to make js wait for the result and treatment of fetch request to continuous on?

I'm still a js beginner and full of doubts. You guys from stack overflow are helping a lot. Thanks!

Context: I want to make a fetch request to my API after the user logs in, and verifies if the user is admin or costumer, so then it continues on. To do so, I need to make another request to the user's endpoint to verify it.

The problem is that javascript doesn't wait for the return of the userRole() function to treat it and then print 'ok' to the console. It prints first!

I've tried a lot of solutions but couldn't make it work.

let userRole = async (id, token) => {
    let response = await fetch(
      `https://lu-teperino-arq-developer.herokuapp.com/usuarios/${id}`,
      {
        method: "GET",
        headers: {
          Authorization: "Basic " + token
        }
      }
    );
    let data = await response.json();

    if (data.profissional === true) return "admin";
    else if (data.profissional === false) return "customer";
    else return "";
  };

  const userId = "";
  const token = "";

  userRole(userId, token).then(data => {
    console.log(data);
  });

  console.log("ok");

Can anyone please help me?

Upvotes: 2

Views: 2674

Answers (2)

Sukanta Bala
Sukanta Bala

Reputation: 879

You should use it by this way:

let checkRole = async (req, res, next) => {
  let userRole = async (id, token) => {
    let response = await fetch(
      `https://lu-teperino-arq-developer.herokuapp.com/usuarios/${id}`,
      {
        method: "GET",
        headers: {
          Authorization: "Basic " + token
        }
      }
    );
    let data = await response.json();

    if (data.profissional === true) return "admin";
    else if (data.profissional === false) return "customer";
    else return "";
  };

  const userId = "";
  const token = "";

  let role = await userRole(userId, token).then(data => {
    console.log(data);
  });

  console.log("ok");
};

Upvotes: 1

matthew-e-brown
matthew-e-brown

Reputation: 3007

You're so close. Currently, only your console.log(data) is waiting for your asynchronous function to finish. You've defined an async function but didn't really await it anywhere. It's not enough to simply define a function as async to be able to put await inside of it. That function now must be either awaited or .then()ed itself.

Think about it: any steps that depend on userRole completing are also awaiting. You cannot have synchronous code depending/waiting on asynchronous code. You're going to have to have the entirety of the process that is waiting for userRole be asynchronous.


If all of your code is waiting on userRole, you could perhaps make window.onload async? I'm not in a work-space where I can test right now, but perhaps try this instead:

window.onload = async () => {
  const userRole = async (id, token) => {
    // current code...
  }

  const data = await userRole('id-123', 'token-abc');

  console.log(data);
  console.log('ok');

  // Now do the rest of your stuff
}

If this isn't the case, then your solution is to just remember that everything after running userRole that's waiting on it is also asynchronous. You'll just have to put the rest of the dependant code in your .then() (or put it all in another async function and use awaits, like I did above, just not with window.onload):

const userRole = async (id, token) => {
  // current code...
}

userRole('id-123', 'token-abc').then(data => {
  console.log(data);
  console.log('ok'); // <-- do it here

  // The rest of the code that needs userRole's response
});

Upvotes: 3

Related Questions