how to return response of axios in return

前端 未结 4 1870
长情又很酷
长情又很酷 2021-02-01 06:09

I want to return the response of axios but always the response that returned is undefined:

wallet.registerUser=function(data){
axios.post(\'http://localhost:8080         


        
4条回答
  •  轮回少年
    2021-02-01 06:46

    You will need to wrap the call to axios in an async function. You can then return the response as you normally would.

    As long as you call the wrapper method with await, you will be fine. Unfortunately, in order to call it with await, the calling method will also have to be marked async, and so on and so on, until every function in your application must be marked async and you will need to call ALL of your functions with await.

    This is the magic and the beauty of the async / await keywords - utter garbage. You may see examples that create an async lambda to wrap the await axios, in an attempt to not have to refactor their entire app, but its not going to work.

    So, the wrapper looks like the following...

    async public post(URL, data) {

    axios.post(URL, data)
        .then( (result) => {
            return result;
        });
    

    }

    If you are using typescript, that will add several more frustrating issues, such as how to cast an any to the type you want to return. I might suggest union types.

    Anyway, good luck!

    P.S. axios won't work if your environment requires using a proxy. In that case, and probably all others, use node-fetch - you will be up and running with node-fetch in a day. Axios will have you scratching your head a week later, wondering why its not working.

提交回复
热议问题