首页 > 解决方案 > 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,并将其保存在我的数据库(猫鼬)中,然后调用一个函数,该函数读取所有保存的数据并将其发送到电报(它是电报机器人)

标签: node.jsasynchronousmongoose

解决方案


最后我决定用建议的数据填充一个数组,然后使用 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();

推荐阅读