Search code examples
javascriptfunctionasync-awaites6-promise

Turning a function into promise doesn't seem to work


I have written a function that works well however, I wanted to turn it into a promise in order to call it in other functions with async/await. I tried to modify the function by inserting a new Promise but I think I have messed up.

async function checkStatus(requestStatus, taskStatus, taskId, ontId) {
  return new Promise(function (resolve, reject) {
    let result;
    console.log("CHECK STATUS FUNCTION REACHED: ", ontId);
    if (requestStatus == 200 && taskStatus == "Received") {
      const date = moment().format("LL");
      let startTime = new Date(Date.now() + 5000);
      let endTime = new Date(startTime.getTime() + 180000);
      const j = schedule.scheduleJob(
        { start: startTime, end: endTime, rule: "*/30 * * * * *" },
        async function () {
          const response = await axios({
            method: "post",
            url: `http://localhost:7788/api/checkProvisioningStatus/${taskId}`,
            data: { ontId },
          });
          result = response.data.status;
          if (
            response.data.status === "Failed" ||
            response.data.status === "Completed"
          ) {
            console.log(
              "%cRESPONSE.DATA.STATUS: ",
              "color: green; font-weight: bold",
              response.data.status
            );
            j.cancel();
          }
        }
      );
      resolve(result);
    } else {
      console.log("Unable to save and provision ONT");
      result = "Failed";
      reject(result);
    }
  });
}

I would greatly appreciate any guidance/assistance in identifying my mistake.


Solution

  • You don't need to create a promise if you use async with await. Change the function to how you had it originally, and call it with let result = await checkStatus();.