[英]Javascript SessionStorage Items not available in first function call
[英]Javascript SessionStorage Checking Before Running a Function
我有一個正在調用的函數。 稱為getStatus()。 但是,此功能需要存在一個定義的SessionStorage變量。 如果存在變量,那么我要繼續執行getJob()函數。 如果不存在,我想嘗試定義SessionStorage變量,然后執行getJob()函數。
像這樣:
function getStatus()
{
if (sessionGet("jwt") != null)
{
getJob(document.getElementById('job').value, document.getElementById('id').value);
}
else
{
var myValue = '{{ myValue }}';
console.log("Token is missing, acquiring another one!");
var nextToken = setTimeout(function(){ getSessionToken(myValue); }, 5000);
console.log("Reissued token issued is");
console.log(nextToken);
getJob(document.getElementById('job').value, document.getElementById('id').value);
}
}
這是讀取SessionStorage變量的函數:
function sessionGet(key) {
let stringValue = window.sessionStorage.getItem(key)
if (stringValue !== null) {
let value = JSON.parse(stringValue)
let expirationDate = new Date(value.expirationDate)
if (expirationDate > new Date()) {
return value.value
} else {
window.sessionStorage.removeItem(key)
}
}
return null
}
當我查看Chrome控制台時,我看到正在寫入SessionStorage變量,但是讀取該變量的getJob()函數卻看不到它。 如果我重試,則getJob()函數能夠讀取它。 我的想法是,在寫入變量之前會觸發getJob()函數。 這就是為什么我在那里嘗試setTimeout()的原因。
有什么建議么?
正如ztadic91指出的那樣,我需要將setTimeout包裝在getJob()函數調用周圍,因為它需要等待創建SessionStorage變量。 這樣做之后,一切都進行了測試。 贊賞快速協助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.