首页 > 解决方案 > 在 Axios 请求中使用 Promise

问题描述

我正在努力找出实现某事的最佳方法。当我登陆个人资料页面时,个人资料组件会加载该个人资料的数据。这是分配给this.profile. 在这个数据中是一个文件的路径,我想使用这个文件处理一些数据。对我来说,下面的方法似乎有点冒险。

created() {
    let vm = this;

    let url = `/api/profile/${this.$route.params.id}`;
    axios.get(url).then(response => {
        this.profile = response.data;

        d3.json(response.data.fileName)
        .then(function (data) {
            //do some stuff

        }).catch(function (error) {
            // handle error
        });
    });
}

相反,我想确保我首先拥有来自 axios 调用的数据。所以我想我需要一个承诺?我在想更多的事情

created() {
    let vm = this;

    let url = `/api/profile/${this.$route.params.id}`;
    axios.get(url).then(response => {
        this.profile = response.data;
    }).then() {
        d3.json(response.data.fileName)
        .then(function (data) {
            //do some stuff

        }).catch(function (error) {
            // handle error
        });
    };
}

但以上是不正确的,主要是为了展示我想要实现的目标。我想知道如何才能使用 deferred 并承诺在 axios 调用后仅执行 d3 的东西。

谢谢

标签: javascriptvue.jsvuejs2

解决方案


这就是async/await派上用场的地方。A 你不需要保存this到变量中,B 你有更干净、更易读的代码。

async created() {

    const url = `/api/profile/${this.$route.params.id}`;
    const { data } = await axios.get(url); // Optional destructuring for less clutter
    this.profile = data;

    const d3Data = await d3.json(data.fileName);
    //do whatever you want

}

推荐阅读