est
est

Reputation: 13

AccessToken from AsyncStorage + request by axios

While writing the application in the react-native I met with a certain obstacle related to promises, so I have a function that is responsible for the authorized request

export const authorizeRequest = async () => {
  const token = await deviceStorage.getItem('accessToken');
  return axios.create({
    timeout: 2000,
    headers: {
      'Authorization': 'Bearer ' + token,
      'Content-Type': 'application/json'
    }
  });
};

in order to get data from it I write code in the style

authorizeRequest().then(a => a.get('http://192.168.0.60:8080/users/echo2/asd')
        .then(response => ToastAndroid.show('Response ' + response.data, ToastAndroid.SHORT))
        .catch(error => ToastAndroid.show('error ' + JSON.stringify(error), ToastAndroid.LONG)))

Is it possible to avoid the first use of .then when calling authorizeRequest().then(....) so that the query looks like authorizeRequest().get('xxx').then(xxx).catch(xxx) Thanks!

Upvotes: 0

Views: 642

Answers (1)

Andrew
Andrew

Reputation: 28539

Why use promise syntax when you are already using async/await syntax to get your value out of the device storage?

You can rewrite your code using async/await which makes it much easier to see what is going on in your code.

export const authorizeRequest = async (url) => {
  try {
    const token = await deviceStorage.getItem('accessToken');
    const a = await axios.create({
      timeout: 2000,
      headers: {
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/json'
      }
    });

    const response = a.get(url);
    ToastAndroid.show('Response ' + response.data, ToastAndroid.SHORT);
    // return response.data // <- you could return something here
  } catch (error) {
    ToastAndroid.show('error ' + JSON.stringify(error), ToastAndroid.LONG);
  }
};

Writing your code in the above way means that you can avoid promise chaining.

You can then use it in the following way:

await authorizeRequest('http://192.168.0.60:8080/users/echo2/asd')

If you want to get a value from the authorizeRequest function you could just return the response.data and you would access it like this:

const data = authorizeRequest('http://192.168.0.60:8080/users/echo2/asd')

Here are some great articles on promises and async/await.

Upvotes: 2

Related Questions