【问题标题】:AccessToken from AsyncStorage + request by axios来自 AsyncStorage 的 AccessToken + axios 的请求
【发布时间】:2019-08-01 01:13:56
【问题描述】:

在 react-native 中编写应用程序时,我遇到了与 Promise 相关的某些障碍,所以我有一个负责授权请求的函数

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

为了从中获取数据,我以风格编写代码

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)))

是否可以在调用authorizeRequest().then(....)时避免第一次使用.then,使查询看起来像authorizeRequest().get('xxx').then(xxx).catch(xxx) 谢谢!

【问题讨论】:

    标签: react-native promise axios


    【解决方案1】:

    当您已经使用 async/await 语法从设备存储中获取价值时,为什么还要使用 promise 语法?

    您可以使用async/await 重写您的代码,这样可以更轻松地查看代码中发生的情况。

    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);
      }
    };
    

    以上述方式编写代码意味着您可以避免承诺链接。

    然后您可以通过以下方式使用它:

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

    如果您想从 authorizeRequest 函数中获取一个值,您只需返回 response.data,您可以像这样访问它:

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

    这里有一些关于promisesasync/await 的精彩文章。

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 1970-01-01
      • 2022-12-16
      • 2019-09-22
      • 2022-09-17
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 2021-07-08
      相关资源
      最近更新 更多