我正在尝试使用 Node.JS 应用程序来发出和接收 API 请求。它使用 Axios 向另一台服务器发出 get 请求,并使用从 API 调用接收到的数据。第二个片段是脚本从调用返回数据时的情况。它实际上会获取数据并将其写入控制台,但不会在第二个 API 中将其发送回。
function axiosTest() {
axios.get(url)
.then(function (response) {
console.log(response.data);
// I need this data here ^^
return response.data;
})
.catch(function (error) {
console.log(error);
});
}
...
axiosTestResult = axiosTest();
response.json({message: "Request received!", data: axiosTestResult});
我知道这是错误的,我只是想找到一种方法让它发挥作用。我似乎可以从中获取数据的唯一方法是通过console.log,这对我的情况没有帮助。
问题是原来的axiosTest()
函数没有返回承诺。为了清楚起见,这是一个扩展解释:
function axiosTest() {
// create a promise for the axios request
const promise = axios.get(url)
// using .then, create a new promise which extracts the data
const dataPromise = promise.then((response) => response.data)
// return it
return dataPromise
}
// now we can use that data from the outside!
axiosTest()
.then(data => {
response.json({ message: 'Request received!', data })
})
.catch(err => console.log(err))
该函数可以写得更简洁:
function axiosTest() {
return axios.get(url).then(response => response.data)
}
或者使用异步/等待:
async function axiosTest() {
const response = await axios.get(url)
return response.data
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)