I commented some descriptions for the main key steps in the code below
when my Html is loaded, there is nothing in web storage(session storage). but some data will be loaded into the storage after 2~3 seconds.
So my problem is that,
if statement --> if(!optionFlag) runs before the function named "waitForLocalStorage"
is there any way(ex promise or async-await) to wait for the function and perform the if statement after receiving
"id" value from the "waitForLocalStorage" function?
//1. get SessionStorage info. if the requested key is not loaded in the storage. it waits
function waitForLocalStorage(key, cb, timer) {
if (!sessionStorage.getItem(key)) return ( timer = setTimeout(waitForLocalStorage.bind(null, cb, key), 100))
clearTimeout(timer)
if (typeof cb !== 'function') return sessionStorage.getItem(key)
return cb(sessionStorage.getItem(key))
}
...
...
let optionFlag = false;
let id = "0";
//2. call the function above. and requested key is "id"
waitForLocalStorage("sessionInfo", function (value) {
id = JSON.parse(value).id;
eventFlag = (id == "3" || id == "2") ? true : false;
console.log("Checked");
}, 10000);
...
...
// 3. if there is requested key in sessionStage, if statement would be executed.
if(!optionFlag) {
//do some work
...
...
}
"promise or async await" could be the solution for my question but I don't know how to apply it to my code.
To summarise my questions,
want to run the if statement( no 3.) after retrieving data from the "waitForLocalStorage" function.
is there any way to break the "waitForLocalStorage" function in case of preventing infinity loop.
please give me your kind advice.