返回 Axios 数据,以便我可以使用它



我正在从我制作的本地 API 中提取一些数据进行测试,并且需要在函数之外使用生成的数据。我是JS的新手,在使用Promises时遇到问题。 这是我的代码:

const axios = require('axios').default;
function price_data () {
return axios.post('http://127.0.0.1:8000/api/token/', {
username: 'parke',
password: 'password'
})
.then(function (response) {
var token = response['data']['access'];
return axios.get('http://127.0.0.1:8000/price', {
headers:{'Authorization': 'Bearer ' + token}
})
.then(function (response) {
var all_data = []
for (i = 0; i < response['data'].length; i ++) {
all_data.push(response['data'][i]['close'])
}
console.log(all_data);
return(all_data)
})
.catch(function (error) {
console.log(error)
})
.catch(function (error) {
console.log(error);
})
})
}
console.log(price_data())

结果如下所示:

Promise { <pending> }
[
1,      1,      1,      1,      1,      1,      1, 1.5907,
1.5318, 1.5318, 1.5907, 1.5907, 1.5907, 1.5907, 1.5907, 1.5318,
1.3551,  1.414,  1.414,  1.414,  1.414, 1.3551, 1.2372, 1.2372,
1.414,  1.414, 1.3551,  1.414,  1.414,  1.414,  1.414,  1.414,
1.414,  1.414,  1.414,  1.414,  1.414, 1.2961, 1.2961, 1.2961,
1.414,  1.414,  1.414,  1.414,  1.414, 1.3551, 1.3551, 1.3551,
1.3551, 1.3551, 1.3551, 1.3551, 1.3551, 1.2961, 1.2961, 1.2961,
1.2961, 1.2961, 1.2961, 1.2961, 1.3551, 1.2961, 1.2961, 1.3551,
1.414,  1.414,  1.414, 1.4729, 1.4729, 1.4729, 1.4729, 1.4729,
1.4729,  1.414,  1.414,  1.414,  1.414,  1.414,  1.414,  1.414,
1.414,  1.414, 1.4729, 1.4729, 1.4729, 1.4729, 1.4729, 1.4729,
1.4729, 1.4729, 1.5907, 1.5613, 1.5907, 1.5465,  1.576, 1.5318,
1.5318, 1.5539, 1.5907, 1.5907,
... 1101 more items
]

我有点理解该函数在控制台打印之前返回.log但我需要获取在函数外部记录的数据。如果有人能很快帮助我,将不胜感激。谢谢!

你应该使用 .then,

console.log(price_data()) // This will return promise
price_data().then((data) => {
console.log(data); // This will contain the final return value from the promise axios.then.
});

承诺的事情是你不能从中提取任何东西,所以你通过 axios 得到的每一个动作都应该与.then()一起使用

在您的情况下,它是price_data().then(data => console.log(data))

在上面的代码中,您调用price_data()函数,该函数返回一个包含一些数据的 promise。之后,您可以使用.then(data => console.log(data))来控制台该数据

我希望它有所帮助,

干杯

编辑: 您可以使用 async/await 将数据从 promise 分配给变量,但您需要将函数包装到异步函数中,如下所示:

async function getData (url) { // this is an async wrapping function
function price_data () { // this is a function that you already have
return axios(url)
}
const result = await price_data() // assign the data from price_data() to a varible using await 
console.log(result) // console your variable
}

在这里,您可以了解有关 async/await 的更多信息

我真的希望它能帮助你

相关内容

最新更新