how to wait to store data in databases with nested loop in NodeJS

Viewed 65

i want to fetch data from api and execute for loop to store all response data in mysql database.then again fetch data from api with different request parameter but it does not wait to complete for loop and store data i have tried async/await but noting works

  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" }));
});

i am executing a for to fetch user details from database then i execute api for each user and saved response data with loop but next api is hitting before saving all data in database it does not wait to complete nested for loop

0 Answers
Related