等到enclosure的异步方法完成javascript

时间:2013-07-11 17:19:57

标签: javascript jquery asynchronous

我是javascript编程的新手。我找不到有效的答案。

问题是我的函数只有当它被包装在setTimeout调用中时才有效:

var sPageIdentifier = 'ReportViewer';
UserPreferencesManager.Initialize(sPageIdentifier);
setTimeout(function () {
var strUserPrefs = UserPreferencesManager.GetPreferences();
    console.log(strUserPrefs);
   initLayout(strUserPrefs);
}, 1000);

function initLayout(strUserPrefs) {
    //do stuff using strUserPrefs
}

如果我注释掉setTimeout函数,则initLayout(strUserPrefs)会失败,因为strUserPrefs为null。 任何帮助将不胜感激!

这是UserPreferencesManager.js代码:

var UserPreferencesManager = function () {
  var strPrefsID = null;
  var strPrefsString = null;

  return {

    Initialize: function (strPrefsIDIn) {
      strPrefsID = strPrefsIDIn;
      strPrefsString = this.GetPreferences();
    },

    GetPreferences: function () {
      if (!strPrefsID) {
        alert("Validation Failed: the UserPreferencesManager must be initialized prior to usage.");
        return null;
      }
      if (!strPrefsString) {
        this.LoadPreferences();
        return strPrefsString;
      }
      return strPrefsString;
    },
    LoadPreferences: function () {
      if (!strPrefsID) {
        alert("Validation Failed: the UserPreferencesManager must be initialized prior to usage.");
        return null;
      }    
      myasyncfunctioncall({
        parameters: ["USR_PersonId", "abc", 'GET']
        script_name: 'MAINTAIN_USER_PREFS',
        onexception: function (exception, xhr, options) {
          alert('Error: ' + xhr.statusText + +exception);
          console.log(exception);
        },
        onsuccess: function (data, xhr, options) {
          if (data == "User ID is zero") {
            alert('MP_MAINTAIN_USER_PREFS: must be > 0.0');
            strPrefsString = data;
          }
          else {
            strPrefsString = data;
          }
        }
      });
    },// end of LoadPreferences

    WritePreferences: function (strPrefsIn, strPrefsID) {
      if (strPrefsID && typeof strPrefsID === "string") {
        if (strPrefsIn != null) {

          myasyncfunctioncall({
            parameters: ["USR_PersonId", strPrefsID, strPrefsIn , 'SET']
            script_name: 'MAINTAIN_USER_PREFS',
            onexception: function (exception, xhr, options) {
              alert('Error: ' + xhr.statusText + +exception);
              console.log(exception);
            },
            onsuccess: function (data, xhr, options) {
              if (data == "transaction-ok") {
                UserPreferencesManager.LoadPreferences();
              } else if (data == "User ID is zero") {
                alert('MP_MAINTAIN_USER_PREFS: must be > 0.0');
              }
            }
          });
        } else {
          alert("Error: Preferences object must be initialized prior to writing preferences");
        }
      } else {
        alert('Error: The preference ID can\'t be null and must to be of type string');
        return;
      }
    }// end of WritePreferences
  };// end of return API

}(); // end of UserPreferencesManager

3 个答案:

答案 0 :(得分:0)

像这样的搜索myasyncfunctioncall正在发送异步请求。如果此异步请求的响应已到达,则需要添加一些变量来设置,然后,当设置它时,您可以继续执行例程。

无论何时对javascript进行异步调用,程序都会继续,就像它已经完成一样。您必须手动添加检查以查看它是否已完成。

答案 1 :(得分:0)

UserPreferencesManager.GetPreferences()正在进行异步AJAX调用以获取用户首选项。因此,在这种情况下,Javascript线程将继续在当前线程上下文中执行并执行initLayout(strUserPrefs)。但是在这种状态下,GetPreferences()调用仍未完成且strUserPrefs为空。

SetTimeout是解决这个问题的技巧之一,你做到了。但您也可以设计API,使其允许为每个异步AJAX调用执行回调函数。

答案 2 :(得分:0)

感谢小费,Balachandra! 这是我做的,为LoadPreferences方法添加了两个参数 - callback和strPrefsID,所以我可以在成功时调用fnCallback函数并将其传递给ajax数据:

LoadPreferences: function (fnCallback, strPrefsID) {
    if (!strPrefsID) {
        alert("Validation Failed: the BhsUserPreferencesManager must be initialized prior to usage.");
        return null;
    }
    if (strPrefsString) {
        // strPrefsString is not null, so return it
        callback(strPrefsString);
    } else {
        myasyncfunctioncall({
            parameters: ["USR_PersonId", "abc", 'GET']
            script_name: 'MAINTAIN_USER_PREFS',
            onexception: function (exception, xhr, options) {
                alert('Error: ' + xhr.statusText + +exception);
                console.log(exception);
            },
            onsuccess: function (data, xhr, options) {
                if (data == "User ID is zero") {
                    alert('MAINTAIN_USER_PREFS: must be > 0.0');
                    strPrefsString = data;
                } else if (data.substring(0, 5) === "ERROR") {
                    alert(data);
                } else {
                    fnCallback(data);
                }
            }
        });
    }
}// end of LoadPreferences

以下是现在我可以调用initLayout的方法:

BhsUserPreferencesManager.LoadPreferences(initLayout, sPageIdentifier);