node.js - Async/Await 函数只返回最后一个结果,而不是 for 中所需的所有结果
问题描述
我有这个代码
for (let i = 0; i < 10; i++) {
if (addresses.includes(jsonResponse[i].address)){
console.log(jsonResponse[i].address + " --> " +jsonResponse[i].balance)
var testbalance = new Balance({address: jsonResponse[i].address, balance: Math.round(Number(jsonResponse[i].balance))}) //saves the top10 richlist addresses
function saveBalance(){
return testbalance.save();
}
}
}
async function sendData() {
const data = await saveBalance(); //this only gets the last result of the for, but i need it to get all the results [0,1,2,3,4,5,6,7,8,9] , but it only saves the [9]
Balance.find({}, function(err, data){
bot.sendMessage(groupId, JSON.stringify(data))
});
}
sendData();
for 基本上读取一个 api,并将其保存在我的数据库(猫鼬)中,然后调用一个函数,该函数读取所有保存的数据并将其发送到电报(它是电报机器人)
解决方案
最后我决定用建议的数据填充一个数组,然后使用 mongoose model.create 来上传它。
终于设法使其异步
var testbalance = [];
//populates testbalance array in order to upload to the DB model
for (let i = 0; i < 10; i++) {
if (addresses.includes(jsonResponse[i].address)){
console.log(jsonResponse[i].address + " --> " +jsonResponse[i].balance)
testbalance.push({
address: jsonResponse[i].address,
balance: Math.round(Number(jsonResponse[i].balance))
})
}
}
//uploads the data
function saveBalance(){
return new Promise ((resolve) => Balance.create(testbalance,function(err) {
if (err);
resolve();
}))
}
//sends the data
async function sendData(){
const data = await saveBalance(); //waits for saveBalance resolution
//sends the data to the tgBot
Balance.find({}, function(err, data){
bot.sendMessage(groupId, JSON.stringify(data))
});
}
sendData();
推荐阅读
- r - 使用超过 30 个预测变量时 MuMin pdredge() 中的错误
- jquery - 如何遍历对象数组并获取值并将单击事件添加到值
- php - 无头 Chromium 浏览器始终显示验证码
- python - 根据相似度百分比连接文件中的多个 seq
- tensorflow - TFLite:是否可以使用 Keras 的 load_model 转换具有不同输入形状的 H5 模型?
- vb.net - 我在 VB.net 中遇到过滤器问题并使用访问数据库
- jquery - 如何在数据表的下拉列过滤中添加自定义选项
- woocommerce - 如何在后台的订单商品表中显示正常价格
- batch-file - 从另一个没有 CALL 的批处理脚本调用带有 LABEL 的批处理脚本
- reactjs - 使用带有条件渲染的钩子