I'm pretty new to javascript and I'm buiding a react/flux app and using jquery to make synchronous "ajax" calls (sjax?) to the backend. I'm getting inconsistent behavior because (I think) my ajax call is not blocking despite using async:false. The key code snips are below.
The execution flow starts in the Flux store with the ActionTypes.LOGIN case, then moves to fetchAccount(action.value);, and should be synchronously followed by AppStore.emitChange();
The issue is if I call AppStore.emitChange(); in my $.ajax success function then I am able to guarantee that AppStore.emitChange(); come after the success function, but otherwise if AppStore.emitChange() comes after the fetchAccount(action.value) call it gets executed before the $.ajax success function completes.
In my Flux Store, I call a helper function and then emit a change:
// Register callback to handle all updates
AppDispatcher.register(function(action) {
var text;
switch(action.actionType) {
case ActionTypes.LOGIN:
fetchAccount(action.value);
//if i put AppStore.emitChange(); here it's invoked
//before fetchAccount completes even though the $.ajax call is async: false
AppStore.emitChange();
break;
//... code ommitted ...
}
});
My helper function executes the ajax call:
function fetchAccount(email) {
$.ajax({
url: "http://www.foo.com/api/accounts/" + email,
jsonp: "callback",
dataType: 'jsonp',
type: 'GET',
async: false,
headers: {"Accept" : "application/javascript; charset=utf-8"},
success: function(data) {
user = data;
currentViewState = AppStates.CONTENT_VIEW;
//AppStore.emitChange(); ---> if i emitChange here it works
},
error: function(xhr, status, err) {
user = "";
currentViewState = AppStates.LOGIN_VIEW;
}
});
};
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. See http://api.jquery.com/jquery.ajax/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.