我正在尝试使用 axios 向 api 发送请求并将 json 响应存储在变量中。当我将响应输出到控制台时,它会显示它,但是当设置等于它的变量并返回所述变量时,我只得到 Promise { } 作为输出。
const { default: axios } = require("axios");
async function getAvgPrice() {
var data = []; // or whatever we would have to declare for a json object
await axios.get("https://api.com/example.json")
.then(function(res) {
console.log(res); // <-- This outputs the correct response to console
data.push(res); // <-- This just doesn't do anything
});
return data;
}
var x = getAvgPrice();
console.log(x); // <-- (Output: Promise { <pending> })
我尝试向 api 发送请求并将响应存储为 json,但只能返回一个承诺。
您需要等待 getAvgPrice();因为它是一个异步函数。 因此
const x = await getAvgPrice();
将会起作用并为您提供实际数据。