我有此代码
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,并将其保存在我的数据库中(猫鼬),然后调用一个函数,该函数读取所有已保存的数据并将其发送到电报(它是电报机器人)
答案 0 :(得分:0)
最后,我决定按照建议的数据填充数组,然后使用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();