Search code examples
javascriptasynchronousaxiosasync.jsexceljs

Axios post request not running in sequence


I am trying to make use of async series correctly but unable to figure how exactly i need to send the data into it for it to move forward with each post request in exactly the same way as it is getting data.

I have an excel file in which i am getting multiple statuses to mark against each ids that are present in the first column. Also there are statuses that need to be deleted and deleting part is not that difficult and i was able to do it without making use of async series but for posting new records I need to make use of async series. The records to be posted are under the columns 'Mark Status 1', 'Mark Status 1 Date', 'Mark Status 2' and so on. So i wrote a script to fetch the records using a for loop and send them off to a function and that function is responsible for modelling data for asyn series. Inside the markStatusCall function if i put a forEach loop and run the call the sequence of the statuses become wrong. It should be like 'Marks Status 1 value', 'Mark Status 2 value' and so on.

I am attaching my code here, please take a look below and to see the excel file here

const Excel = require("exceljs");
const axios = require("axios").default;
const https = require("https");
const _async = require("async");

const instance = axios.create({
  httpsAgent: new https.Agent({
    rejectUnauthorized: false,
  }),
});
const returnedId = "5dd7fa20dcfa9600152cc2de";
const deliveredId = "5dd7fa20dcfa9600152cc2d3";
const returnedByVendorId = "5de7c418362e13001212f238";
const returnedToVendor = "5eb2ebfe02987816aad14269";
const atSwyftWarehouse = "5dd7fa20dcfa9600152cc2d8";
const reAttempted = "5e6ea5d87aa7bb6d726b2bbc";
const requestToReattempt = "5ee134230138634c27a6e1da";
const dispatched = "5dd7fa20dcfa9600152cc2e2";
const parcelAssignedDelivery = "5dd7fa20dcfa9600152cc2e3";
const cancelledByVendor = "5de7c418362e13001212f238";
var workbook = new Excel.Workbook();
workbook.xlsx.readFile("./1.xlsx").then(async function () {
  // use workbook

  var worksheet = workbook.getWorksheet("Interim");

  const parcelIds = [];
  const status = [];
  const date = [];
  var data = [];
  var finalData = [];

  for (let i = 2; i <= 10; i++) {
    worksheet.getRow(i).eachCell((cell, index) => {
      if (cell.value !== "") {
        worksheet.getColumn(index).eachCell((colCell, indexing) => {
          if (indexing === 1) {
            if (colCell.value === "Delete Status 1") {
              deleteData(i, cell);
            } else if (colCell.value === "Delete Status 2") {
              deleteData(i, cell);
            } else if (colCell.value === "Delete Status 3") {
              deleteData(i, cell);
            } else if (colCell.value === "Delete Status 4") {
              deleteData(i, cell);
            } else if (colCell.value === "Delete Status 5") {
              deleteData(i, cell);
            } else if (colCell.value === "Mark Status 1") {
              markData(i, index, cell);
            } else if (colCell.value === "Mark Status 2") {
              markData(i, index, cell);
            } else if (colCell.value === "Mark Status 3") {
              markData(i, index, cell);
            } else if (colCell.value === "Mark Status 4") {
              markData(i, index, cell);
            } else if (colCell.value === "Mark Status 5") {
              markData(i, index, cell);
            }
          }
        });
      }
    });
  }
  function markData(i, index, cell) {
    let row = worksheet.getRow(i);
    let date = row.getCell(index + 1).value;
    let parcelId = row.getCell(1).value;
    if (cell.value !== "" && date !== "") {
      let statusId =
        cell.value === "At Swyft Warehouse"
          ? atSwyftWarehouse
          : cell.value === "Dispatched"
          ? dispatched
          : cell.value === "Reattempted"
          ? reAttempted
          : cell.value === "Delivered"
          ? deliveredId
          : cell.value === "Cancelled"
          ? returnedId
          : cell.value === "Request for Reattempt"
          ? requestToReattempt
          : cell.value === "Parcel Assigned"
          ? parcelAssignedDelivery
          : cell.value === "Cancelled by Vendor"
          ? cancelledByVendor
          : deliveredId;
      console.log(parcelId, statusId, date);
      addStatus(parcelId, statusId, date);
    }
  }
  // Need help from here
  function addStatus(parcelId, statusId, date) {
    let values = {
      parcelId: parcelId,
      statusRepositoryId: statusId,
      createdAt: date,
      updatedByScript: true,
    };
    data.push(values);
  }

  finalData.push(() => markStatusCall(data));
  _async.series(finalData, (err, data) => {
    if (err) {
      console.log(err);
    }
  });

  async function markStatusCall(values) {
    console.log(values, "Came here");
    values.forEach((data) => {
       try {
      let response = await instance.post(
        "https://api.myDomain.com:3000/api/ParcelStatuses",
        {
          parcelId: data.parcelId,
          statusRepositoryId: data.statusRepositoryId,
          createdAt: data.createdAt,
          updatedByScript: data.updatedByScript,
        }
      );
      console.log("Updated");
    } catch (err) {
      console.log("here");
      console.error(err);
    }
    })
  }

Solution

  • Would something like this work:

    async function markStatusCall(values) {
      console.log(values, "markStatusCall begin");
      
      function loop(values, index) {
        console.log('loop at index', index);
        const data = {
          parcelId: data.parcelId,
          statusRepositoryId: data.statusRepositoryId,
          createdAt: data.createdAt,
          updatedByScript: data.updatedByScript};
    
        try {
          let response = await instance.post("https://api.myDomain.com:3000/api/ParcelStatuses", data);
          console.log("Updated");
          if (index <= (values.length -1)) {
            loop(index + 1);
          } else {
            return;
          }
        } catch (err) {
          console.log("Error");
          console.error(err);
        }
      }
    
      await loop(values, 0);
    }
    

    The idea is that the loop waits for each POST request before moving onto the next item in the values array. (might be some typos in the code above).

    See this example on codepen