Search code examples
javascriptnode.jsstringasynchronouses6-promise

If statement not working with a global variable


when using if(typeof(global.payload) == typeof("")) it does not execute the code inside the block even though typeof(global.payload) returns string

my code:

const { uploadFileToCloud } = require("./app.js")
const path = require("path");
var startTime, endTime;
global.payload = null
var download_size = 448800;
console.log("measurement started")
endTime = new Date().getTime()
console.log("start time => " + endTime)


const measureUpSpd = async () => {
  await uploadFileToCloud("uploadPayload.txt", (path.resolve("./").replace(/\\/g, "/") + "/")).then(response => {
    global.payload = response
    console.log("payload => " + global.payload)
    return (response)
  })
};
measureUpSpd().then(x => {
  console.log("payload => " + global.payload + "  ")
})

if (typeof (global.payload) == typeof ("")) {
  console.log("measurement started")
  global.startTime = new Date().getTime();
  console.log("end time => " + startTime);
  ShowData();
  global.payload = null
}

async function ShowData() {
  var duration = (endTime - startTime) / 1000;
  var bitsLoaded = download_size * 8;
  var speedMbps = ((bitsLoaded / duration) / 1024 / 1024).toFixed(2);
  console.log("Speed: " + speedMbps + " Mbps");
}

uploadFileToCloud();

async function uploadFileToCloud(fileName, filePath) {
  try {
    global.filePathPatched = "" + filePath + fileName
    if (filePath) {
      console.log("compete file path is " + filePathPatched)

      var mimetype = await findMimeType(fileName)
      var folderNameParsed = JSON.parse(fs.readFileSync("./settings.json")).folderId
      const response = await drive.files.create({
        requestBody: {
          name: fileName,
          MimeType: mimetype,
          parents: [folderNameParsed]
        },
        media: {
          mimeType: mimetype,
          body: fs.createReadStream(filePathPatched)
        }

      })
      return (response.data.id + "")
    } else {
      console.log("no file path")
    }


  } catch (error) {
    console.log(error.message)
  }
}

Solution

  • This is a very typical case of asynchronous code management.

    You either need to place your code in the then callback:

    measureUpSpd().then(x => {
      console.log("payload => " + global.payload + "  ")
      if (typeof (global.payload) == typeof ("")) {
        console.log("measurement started")
        global.startTime = new Date().getTime();
        console.log("end time => " + startTime);
        ShowData();
        global.payload = null
      }
    })
    

    Or wrap everything in an async IIFE and await the result from measureUpSpd:

    (async() => {
      const x = await measureUpSpd();
      console.log("payload => " + global.payload + "  ")
    
      if (typeof (global.payload) == typeof ("")) {
        console.log("measurement started")
        global.startTime = new Date().getTime();
        console.log("end time => " + startTime);
        ShowData();
        global.payload = null
      }
    )();