Javascript 如何确保异步方法已完成

Javascript 如何确保异步方法已完成,javascript,jquery,asynchronous,Javascript,Jquery,Asynchronous,我使用的是使用JavaScript的异步/承诺方法 以下是我的代码片段: 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_sta

我使用的是使用JavaScript的异步/承诺方法

以下是我的代码片段:

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”条件,并抛出一个erro。在继续执行之前,如何确保结果可用?

将if条件移动到回调函数中

func(session_id).then(function(res) {
    localStorage.setItem('session_state', res);
    if (localStorage.getItem('session_state') == inactive)
        alert("Session Inactive !");
});

如果您想确保它也被设置为
。那么()

var func=new instance.web.Model(“session.table”).get_func(“check_session_state”)


我还推荐您的代码。

在回拨中包含与会话相关的代码。请参阅。$。AJAX
func(session_id)
.then(function(res) {
    localStorage.setItem('session_state', res);
})
.then(function(){
  if (localStorage.getItem('session_state') == inactive) {
    alert("Session Inactive !");
  }
});