javascript - 返回 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
]
我有点理解该函数在 console.log 打印之前返回,但我需要获取在函数之外记录的数据。如果有人能快速帮助我,将不胜感激。谢谢!
解决方案
Promise 的问题是您无法从中提取任何内容,因此您通过 axios 获得响应的每个操作都应与.then()
在你的情况下price_data().then(data => console.log(data))
在上面的代码中,你调用price_data()
了函数,它返回一个带有一些数据的承诺。之后,您可以.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
}
我真的希望它会帮助你
推荐阅读
- vue.js - 在 Vue.js 基于模板的功能组件中,如何传递完整的上下文?
- java - Restlet 使用不同的 HTTP 方法路由相同的 API
- javascript - 如何在 Angular 中使用高图表?
- java - 休眠无法加载类[]
- c++ - CPLEX - 降低成本
- audio - Raspberry Pi 音频通过以太网
- c++ - 使用浮点精度时,C++ 随机为相同的 Mersenne Twister 种子产生不同的数字
- python - Flask 没有从 cul 正确编码形式
- mysql - 如何从采购价格中计算商品?
- java - 在 Java Web App 中检索大量数据并将其下载到客户端