1

When I have the following function:

axios
      .get(
        `${config.server}/getUsers.php`,
        { headers: { Authorization: `Bearer ${token}` } }
      )
      .catch((error) => console.error(error));

I can do something after I receive the users with .then().

But what, if I put this request in a function:

const getUsers = () => {
   axios
      .get(
        `${config.server}/getUsers.php`,
        { headers: { Authorization: `Bearer ${token}` } }
      ).then(() => {
          return true;
      })
      .catch((error) => {
          console.error(error)
          return false;
      });
};

How can I do something if getUsers() is done and true?

Nick Rick
  • 75
  • 6
  • 2
    `return axios.get()` and then `getUsers.then()`. You have to propogate the promise. – zero298 May 04 '21 at 18:34
  • 1
    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) – zero298 May 04 '21 at 18:34
  • just remove the curlies and the useless `then` and `catch`: `const getUsers = () => axios.get(....)`, that's it. – georg May 04 '21 at 18:45

3 Answers3

4

You can't await a function. You can only await a promise (or other thenable).

If getUsers() returned a promise, then you could call it and await its return value:

await getUsers();

However, it doesn't. So before you can do that you have to change it so it does return a promise.

return axios.get...
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

You can refactor your code like this:

const async getUsers = () => {
  try {
    let users = await axios({
      method: 'get',
      url: `${config.server}/getUsers.php`,
      headers: { Authorization: `Bearer ${token}` }
    });
    return {success: true, result: users};
  } catch (error) {
    return {success: false, error};
  }
};

If the request was successful you can return success: true with result data. If the request failed for some reason you can return success: false and the error.

NOTE: When you use async syntax, the function will return a Promise, so you can do .then() when you call getUsers() is some other function, or you can also use async syntax.

With .then() it will look something like:

someOtherFunction() => {
  getUsers().then((users)=>{
    res.status(200).json();
  }).catch((error))=>{
    res.status(400).json(error);
  }
}

With async it will look something like:

async someOtherFunction() => {
  try {
    let users = await getUsers();
    res.status(200).json(users);
  } catch (error) {
    res.status(400).json(error);
  }
}
NeNaD
  • 18,172
  • 8
  • 47
  • 89
1

Solution

The Axio-Request is a promise, and therefore, it needs to be wrapped and returned to be thenable:

Like this:

const getUsers = () => {
  return axios
    .get(`${config.server}/getUsers.php`, {
      headers: { Authorization: `Bearer ${token}` },
    })
    .then(() => {
      return true;
    })
    .catch(error => {
      console.error(error);
      return false;
    });
};

which would let you do something like this:

getusers().then((returnedReqData)=>{
    console.log(returnedReqData);
})

This is a good resource for learning how to work with promises, and how to make them thenable.

JΛYDΞV
  • 8,532
  • 3
  • 51
  • 77