[英]How to run my async statement after executing some function and break for preventing infinity loop
我评论了下面代码中主要关键步骤的一些描述
当我的 Html 被加载时,web 存储(会话存储)中没有任何内容。 但有些数据会在 2~3 秒后加载到存储中。
所以我的问题是,
if 语句 --> if(!optionFlag) 在名为“waitForLocalStorage”的 function 之前运行
有什么方法(例如 promise 或 async-await)等待 function 并在收到后执行 if 语句
来自“waitForLocalStorage”function 的“id”值?
//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
...
...
}
“承诺或异步等待”可能是我的问题的解决方案,但我不知道如何将它应用到我的代码中。
总结我的问题,
想要在从“waitForLocalStorage”function 检索数据后运行 if 语句(第 3 个)。
在防止无限循环的情况下,有什么方法可以打破“waitForLocalStorage”function。
请给我你的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.