katie hudson
katie hudson

Reputation: 2893

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. 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. 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.

Thanks

Upvotes: 0

Views: 8007

Answers (3)

sandrooco
sandrooco

Reputation: 8716

That's where async/await comes in handy. A you don't need to save this to a variable and B you have cleaner, more readable code.

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

}

Upvotes: 2

Isaac Vidrine
Isaac Vidrine

Reputation: 1666

You can solve this by chaining promises, assuming that d3.json returns a 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
      })
}

Upvotes: 2

Per Digesen
Per Digesen

Reputation: 99

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

Upvotes: 0

Related Questions