我正在使用 JavaScript 的异步/promise 方法
以下是我的代码片段:
var func = new instance.web.Model("session.table").get_func("check_session_state");
func(session_id).then(function(res) {
localStorage.setItem('session_state', res);
});
if (localStorage.getItem('session_state') == inactive)
alert("Session Inactive !");
问题是在设置 session_state 变量之前调用“if”条件,并引发错误。在继续执行之前如何确保结果可用?
最佳答案
如果您想确保它也设置了 .then()
您的 if 代码:
var func = new instance.web.Model("session.table").get_func("check_session_state");
func(session_id)
.then(function(res) {
localStorage.setItem('session_state', res);
})
.then(function(){
if (localStorage.getItem('session_state') == inactive) {
alert("Session Inactive !");
}
});
我还会推荐jshinting你的代码。
关于javascript - 如何确保异步方法已完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26908274/