使用if(typeof(global.payload) == typeof(""))它時即使typeof(global.payload)回傳也不執行塊內的代碼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)
}
}
uj5u.com熱心網友回復:
這是一個非常典型的異步代碼管理案例。
您要么需要將代碼放在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
}
)();
uj5u.com熱心網友回復:
measureUpSpd是一個async功能,它看起來不像你正在await學習。我的猜測是if(typeof(global.payload) == typeof(""))檢查在measureUpSpd完成之前發生并實際設定global.payload為字串值
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/456695.html
標籤:javascript 节点.js 细绳 异步 es6-承诺
