javascript - 访问 promise 值 axios

标签 javascript vue.js axios

我正在尝试从另一个函数的 Axios 调用访问 promise 值。

methods: {
    checkItem() {
        const url = "http://api.crossref.org/journals/" + this.editedItem.issn;
        return axios.get(url)
            .then(response => response.status);
    },

    save() {
        console.log(this.checkItem());
    }
}

我希望在调用 save() 时将状态代码记录在控制台中。目前,它正在记录整个 promise 。

最佳答案

您可以使用async/await

<script>
new Vue({
  el: "#root",

  methods: {
    checkItem() {
      const url = "http://api.crossref.org/journals/" + this.editedItem.issn;
      return axios.get(url).then(response => response.status);
    }
  },
  async save() {
    console.log(await this.checkItem());
  }
});
</script>

或者使用Promise:

<script>
new Vue({
  el: "#root",

  methods: {
    checkItem() {
      const url = "http://api.crossref.org/journals/" + this.editedItem.issn;
      return axios.get(url).then(response => response.status);
    }
  },
  save() {
    this.checkItem().then(res => {
      console.log(res);
    });
  }
});
</script>

关于javascript - 访问 promise 值 axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57188998/

相关文章:

javascript - 如何将字符串转换为 JavaScript 函数调用?

javascript - 单击第二个按钮后,VueJs 不删除图像

javascript - 调用后的Vuejs axios变量分配

javascript - 在渲染到页面之前如何处理 API 响应中的空对象?

asp.net - 卸载页面自定义保存提示?

javascript - 使用 jquery、javascript 和 html 在单击浏览按钮上显示带有进度条的文本框中的文件上传百分比

python - 如何解决错误 405 方法不允许,对于 django graphql 服务器和前端 react axios

javascript - 从 VueJS 中的 "inline-template"调用组件方法

javascript - 带有 vue.js 的 img url

node.js - 使用 AXIOS (Node.js) 在请求之间保留 cookie