如何在nodejs中使用嵌套循环等待在数据库中存储数据

g6ll5ycj  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(211)

我想从api中获取数据并执行for循环,以将所有响应数据存储在mysql数据库中。然后再次使用不同的请求参数从api中获取数据,但它不会等待完成for循环并存储数据,我尝试了async/await,但没有注意到这一点

app.get("/api/garudaTx", (req, res) => {
  let sql = "SELECT * FROM table_name ORDER BY id ";
  let query = conn.query(sql, (err, results) => {
  (async function () {
  for (let i = 0; i < results.length; i++) {
    const element = results[i];
    console.log(element.userAddress);
    console.log(element.id);
    try {
     let response = await axios.get(
      `https://api.bscscan.com/apimodule=account&action=txlist&address=${element.userAddress}&startblock=1&endblock={blockNo}&sort=asc&apikey=`
         );

      let last = await (async function () {
         console.log(response);
        if (response.status != 200 || response.data.result.length == 0) {
          let code = response.status.toString();
          fs.appendFile("responseError.txt", code + "    ", (err) => {
            if (err) throw err;
            console.log("The lyrics were updated!");
          });
          fs.appendFile(
            "responseError.txt",
            element.userAddress + "   ",
            (err) => {
              if (err) throw err;
              console.log("The lyrics were updated!");
            }
          );
        }

        let body = response.data;
        console.log(response.data.result.length);

        const promises = [];
         for (var index = 0; index < response.data.result.length; index++) {
          let data = {
            blockNumber: body.result[index].blockNumber,
            timeStamp: body.result[index].timeStamp,
            hash: body.result[index].hash,
            nonce: body.result[index].nonce,
            blockHash: body.result[index].blockHash,
            from_address: body.result[index].from,
            contractAddress: body.result[index].contractAddress,
            to_address: body.result[index].to,
            value: body.result[index].value,
            transactionIndex: body.result[index].transactionIndex,
            gas: body.result[index].gas,
            gasPrice: body.result[index].gasPrice,
            gasUsed: body.result[index].gasUsed,
            cumulativeGasUsed: body.result[index].cumulativeGasUsed,
            confirmations: body.result[index].confirmations,
           };

           promises.push(
            new Promise((resolve) => {
               let sql = "INSERT INTO table_name SET ?";
               resolve(
                 conn.query(sql, data, (err, results) => {
                   if (err) throw err;
                   console.log(
                     JSON.stringify({
                      status: 200,
                      error: null,
                      response: results,
                     })
                   );
                 })
               );
             })
           );
         }
        await Promise.all(promises);
       })();
     } catch (err) {
      console.log(err);
     }
   }
 })();
 });
 res.send(JSON.stringify({ status: 200, error: null, response: "success" }));
});

我正在执行for从数据库中获取用户详细信息,然后我为每个用户执行api,并使用循环保存响应数据,但在保存数据库中的所有数据之前,下一个api将命中,它不会等待完成嵌套for循环

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题