If 语句不适用于全局变量

If statement not working with a global variable

当使用 if(typeof(global.payload) == typeof("")) 时它不会执行块内的代码,即使 typeof(global.payload) returns string

我的代码:

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

measureUpSpd 是一个 async 函数,它看起来不像你在 awaiting。我的猜测是 if(typeof(global.payload) == typeof("")) 检查发生在 measureUpSpd 完成之前,实际上将 global.payload 设置为字符串值

这是一个非常典型的异步代码管理案例。

您需要将代码放在 then 回调中:

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

或者将所有内容包装在异步 IIFE 中并等待 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
  }
)();