简体   繁体   English

在Axios请求中使用Promise

[英]Using promises in Axios requests

I am trying to work out the best way to achieve something. 我正在尝试找出达成目标的最佳方法。 When I land on a Profile page, the Profile component loads the data for that profile. 当我进入“个人档案”页面时,“个人档案”组件会加载该个人档案的数据。 This is assigned to this.profile . 这已分配给this.profile Within this data is a path to a file, where I want to process some data using this file. 该数据中包含文件的路径,我要在其中使用该文件处理一些数据。 To me, the below approach seems slightly risky. 对我而言,以下方法似乎有些冒险。

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

Instead of that, I want to ensure that I first have the data from the axios call. 取而代之的是,我要确保首先获取来自axios调用的数据。 So I am thinking I need a promise? 所以我想我需要一个诺言吗? I was thinking something more along the lines off 我在想些什么

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

But the above is incorrect, it is mainly to show what I am trying to achieve. 但是以上内容是不正确的,主要是为了显示我要实现的目标。 I was wondering how I can maybe use deferred and promises to only execute the d3 stuff once the axios call is made. 我想知道如何使用deferred并答应仅在axios调用完成后才执行d3。

Thanks 谢谢

You can solve this by chaining promises, assuming that d3.json returns a promise: 您可以通过链接promise解决此问题,假设d3.json返回promise:

created() {
    let vm = this;
    let url = `/api/profile/${this.$route.params.id}`;
    axios.get(url)
      .then(response => {
        this.profile = response.data
        return d3.json(response.data.fileName)
      }).then(data => {
        //do some stuff
      }).catch(err => {
        //log error
      })
}

That's where async/await comes in handy. 这就是async/await派上用场的地方。 A you don't need to save this to a variable and B you have cleaner, more readable code. 一个你并不需要保存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

}
async created() {
let vm = this;

let url = `/api/profile/${this.$route.params.id}`;
try {
const {data} = await axios.get(url)

const d3Data = await d3.json(data.fileName)
    } catch(err) {
      //error
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM