【问题标题】:Async/Await funcion only returning the last result instead all the results desired in a forAsync/Await 函数只返回最后一个结果,而不是 for 中所需的所有结果
【发布时间】:2019-12-02 11:34:43
【问题描述】:

我有这个代码

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.js asynchronous mongoose


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-27
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2019-04-08
    相关资源
    最近更新 更多