javascript - Vue.js axios 从本地存储(localforage)获取值返回promise对象而不是值

标签 javascript local-storage vuejs2 axios localforage

我正在尝试从 localforage 中获取一个值对于 axios打电话,但它不工作。

axios.get('https://api.example.org/api/?uname=' + this.$getItem('LSuname'), {
  withCredentials: true,
  headers: {'Authorization': 'Bearer ' + this.$getItem('LSmytoken')}
})

我在控制台中收到 403 错误:

XHR failed loading: GET "https://api.example.org/api/?uname=[object%20Promise]".

我也尝试过 this.$getItem('LSuname').then(value => { return value })this.$getItem('LSuname').then( function (value) { return value }) 但我得到了完全相同的 403 和错误的 url,最后有一个 promise

我可以像这样在我的 vue 的其他地方正确地返回值而不会出现问题:

this.$getItem('LSuname').then(value => {
  console.log('uname:' + value)
})

最佳答案

看起来 this.$getItem 是一个异步调用,它将返回一个 Promise。这意味着您必须等待该调用完成,然后才能调用任何依赖于这些异步调用的返回值的代码。

在您的情况下,您可以使用 Promise.all()在进行 axios.get 调用之前等待所有异步调用返回:

let unamePromise = this.$getItem('LSuname');
let mytokenPromise = this.$getItem('LSmytoken');

Promise.all([unamePromise, mytokenPromise]).then((vals) => {
  axios.get('https://api.example.org/api/?uname=' + vals[0], {
    withCredentials: true,
    headers: {'Authorization': 'Bearer ' + vals[1] }
  })
})

关于javascript - Vue.js axios 从本地存储(localforage)获取值返回promise对象而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45677627/

相关文章:

javascript - vue js 中组件加载时默认点击按钮

javascript - 为什么我会得到未定义错误的属性?

javascript - localStorage onload 显示我选择的 div?

javascript - JS 代码仅在第一组文本上将行换行,对其余文本不执行此操作

javascript - 如何检索以前的 localStorage 值?

javascript - Vue 多选槽插入符下拉选项显示和隐藏

unit-testing - 如何在 JEST 测试中模拟全局 Vue.js 变量

javascript - 在运行 apache 的 blueonyx 服务器上找不到文件

google-chrome-extension - 如何在使用变量值作为键名称的chrome扩展程序中使用chrome.storage?

javascript - 登录成功后如何更新ApolloClient授权头?