简体   繁体   English

Axios get function undefined when access outside,不能使用async和await

[英]Axios get function undefined when accessing outside, cannot use async and await

The following code gives me undefined.下面的代码给了我未定义的。 I tried fixing it with various async/await but it came up as an error.我尝试用各种 async/await 修复它,但它出现了一个错误。 Anyone know how to fix?有谁知道如何解决? EDIT: To be more specific, I need the value of "output" stored.编辑:更具体地说,我需要存储“输出”的值。 I am using console.log just to guarantee it is getting the information I need it to have.我使用 console.log 只是为了保证它获得了我需要的信息。

const URL = 'https://api.1inch.exchange/v3.0/1/quote?fromTokenAddress=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&toTokenAddress=0x6b175474e89094c44da98b954eedeac495271d0f&amount=1&protocols=';
function getAmount(){
    axios.get(URL).then((response) => {
    //console.log(response.data)
    const output = response.data.toTokenAmount
    //console.log(output)
    return output
})
//console.log(output)  
}
console.log(getAmount());

You must return promise inside getAmount function.您必须在getAmount function 中返回 promise。 Also you need to wait on that promise when calling getAmount function.此外,在调用getAmount function 时,您还需要等待 promise。 This should work:这应该有效:

const URL = 'https://api.1inch.exchange/v3.0/1/quote?fromTokenAddress=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&toTokenAddress=0x6b175474e89094c44da98b954eedeac495271d0f&amount=1&protocols=';
function getAmount(){
    return axios.get(URL).then((response) => {
    const output = response.data.toTokenAmount
    return output; })
}

getAmount().then(toTokenAmount => console.log(toTokenAmount));

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

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