【发布时间】:2021-05-13 05:53:10
【问题描述】:
这是我路线中的代码:
const hotspots = await Hotspot.find({user: req.user._id});
if(!hotspots) return res.render("hotspot");
let hotspotData = [];
let rewards = [];
function getApiData(){
return new Promise((resolve,reject)=>{
let error = false;
for (let hotspot of hotspots){
axios.get(`https://api.helium.io/v1/hotspots/${hotspot.hotspot}`)
.then((resp)=>hotspotData.push(resp.data));
axios.get(`https://api.helium.io/v1/hotspots/${hotspot.hotspot}/rewards/sum`)
.then((resp)=> {
console.log("first console log",resp.data.data.total)
rewards.push(resp.data.data.total) ;
console.log("Data gained from axios",resp.data.data.total);
})
}
if(!error) resolve();
else reject("Something went wrong");
})
}
getApiData().then(()=> {
console.log(hotspotData);
console.log(rewards);
res.render("hotspot",{hotspots: hotspotData, rewards: rewards});
});
其他一切都很好,但是当我记录 hotspotData 和 rewards 时,我得到了一个空数组,但正如你所见,我已经将我从 API 获得的数据分别推送到了这些数组。但是 sti;;我得到空数组。请帮我。我已经记录了 API 数据,是的,它正在发送正确的数据,但我不知道为什么这些数据没有被推送到数组中。
编辑:这是表明我的代码没有按照我想要的方式执行的输出:
【问题讨论】:
-
检查事件循环是如何工作的,以及如何使用 async/await 代替 Promise,它也会让你的代码更容易阅读
-
这种承诺方法运行良好。只是数据没有被推送到数组中,我想知道为什么
-
它不起作用,因为promise方法不起作用嘿嘿让我在答案中写几个例子,给我一点时间
标签: javascript node.js asynchronous promise