简体   繁体   中英

Javascript get data from promise (axios)

I am making a Vue.js web-app and I am running into some javascript issues. I will describe the entire Vue.js setup just in case, but I don't think its really relevant. I know that there are other postss on this issue, but after a day and a half of trying to figure it out I couldn't find any posts that helped me enough to figure it out.

The problem :

I am trying to access data from my backend in my frontend. I am using an axios request that looks as follows:

axios.request({...}).then(function (response) { ... }.catch(function (error) { ... });

The response in the .then gets the correct data I want (an array) but I can't figure out how to get that data out, since the .then is a promise. The reason I need to get it out is because this is all inside a in a method inside a component and I want to equate the response to a value in my data variable. So basically I want to do:
this.myvar = this.myvar.concat(response)
but inside the .then I am outside of the scope of my component, so I want to get the response out of the .then so that I can change my data to it.

I understand that theoretically I can append more .then s to do what I want with the response, and that is how javascript handles the synchronicity, but there is nothing I want to do with the data, other than make an out-of-scope variable equal to it.

My attempt:

One thing I found is that I can declare a separate variable right before the axios request, and for some reason that variable will be available to me inside the .then . So I tried initializing a new variable to be a pointer to the component data variable that would be out-of-scope ( this.myvar ) and then change that variable in the .then to the response, but then that reaises other issues because I end up returning my function (that contains the axios request and everything) before that variable gets changed inside the .then do to the synchronicity and that causes other issues.

Edit: My code this is a computed method inside a component. It has to return this.myvar as it is called inside a Vuejs template.

MyFunc: function () {  
    var a = this.myvar;                                                                                            
    axios.request({                                                                                                
        method: 'post',                                                                                              
        url: 'http://myURL:MyPort/query',                                           
        data: {                                                                                                      
           'mydata': dataToSend                                                                                                         
        },                                                                                                           
    }).then(function (response) {                                                                                  
        a = a.concat(Object.values(response.data.results));                                                        
    }).catch(function (error) {                                                                                           
        console.log(error);                                                                                          
    });
    return this.myvar
}                   

This is not the first time I have had problems with promises in javascript, I have tried reading up on them but I just can't understand completely how to deal with them. Any help would be grteatly appreciated.

If this is within a Vue component, then you need to understand some concepts:

a) A computed property can not be asynchronous. It needs to return a value right away, from values already available

b) You can request asynchronous values using axios, and when you get the response, you just assign the value into a property in the component data

data: () => {
    return {
        dataFromServer: undefined,
    };
},
methods: {
    getDataFromServer() {
        axios.get(url)
            .then(response => response.data)
            .then(data => {
                this.dataFromServer = data;
            })
    },
},

c) Finally, if you need a computed property from a value that comes from the server, you define it like this:

computed: {
    derivedValue() {
        return this.dataFromServer? this.dataFromServer * 2 : undefined;
    },
}

Initially, derivedValue will be undefined, as it depends on a value that is not yet available. However, as soon as the value returns from server and you assign it to this.dataFromServer , Vue.js will work it's magic, and will automatically recalculate derivedValue , updating every place where it appears.

It is important to realize that in your template you can use either dataFromServer or derivedValue . And also, take into account that for a short time, those values will be undefined, until the server response gets back to you.

You don't need to do anything special; You can return the data from the .then block as follows:

axios.request({...})
.then(function (response) { 
  return response.data;  // Or assign it to a variable or state in your app
}
.catch(function (error) { 
  ...
});

jsfiddle example: https://jsfiddle.net/rj4pgwek/

you can try using async and await to make async function so the function may look like this without the need of

.then

const myAsyncFunc = async () => {
    const axiosURI = 'Some_URI_To_call'
    const res = await axios.post(axiosURI, {
      params:{}
    });
}

the result will be in the res variable so you can use it to get clone to res into another variable to be reusable in some place else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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