【问题标题】:Get value from promise react native and cominbing to Axios header从 Promise react native 中获取价值并结合到 Axios 标头
【发布时间】:2021-05-24 03:21:32
【问题描述】:

我是 react native 的新手,所以我想从函数中获取价值并将其组合到 axios 标头中。

const getSecurityKey = async () => {
    try {
        const securityKey = await AsyncStorage.getItem('@securityKey')
        return securityKey != null ? JSON.parse(securityKey) : null
    } catch (e) {
        return false
    }
}

instance.interceptors.request.use(function (config) {

    config.headers['X-Security-Key'] = getSecurityKey()

    return config
}, function (error) {
    return Promise.reject(error)
})

这怎么可能得到价值

【问题讨论】:

  • 您的securityKey 是否已经返回已解决的承诺?如果是这样,请尝试以下操作(您需要使拦截器异步):instance.interceptors.request.use(async function (config) { config.headers['X-Security-Key'] = await getSecurityKey() return config; }...
  • 感谢您的回答,它有效!
  • 刚刚发布了答案,供未来的编码员使用!

标签: javascript ecmascript-6 axios react-native-android


【解决方案1】:

您需要使您的 interceptors 异步,例如:

instance.interceptors.request.use(async function(config) {
  config.headers['X-Security-Key'] = await getSecurityKey();
  return config;
}, function (error) {
  return Promise.reject(error);
});

【讨论】:

    猜你喜欢
    • 2021-11-10
    • 2018-06-06
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2023-03-18
    • 2017-11-01
    相关资源
    最近更新 更多