我可以想象你的代码正在做类似的事情
var userIsSignedIn;
updateUI(event);
syncCall();
nextThing(userIsSignedIn);
anotherThing();
moreThings();
对syncCall进行简单的更改 - 称为asyncCall,以免混淆
function asyncCall(cb){
$.ajax({
dataType: 'json',
type: 'GET',
url: '/calls/synccall',
success: function (json) {
cb(json.is_signed_in);
}
});
}
你的代码重写:
updateUI(event);
asyncCall(function(userIsSignedIn) {
nextThing(userIsSignedIn);
anotherThing();
moreThings();
});
注意缺少var userIsSignedIn;
必需的
对于改善最终用户体验来说确实是一个小小的改变
第二种选择是将您提供的所有代码包装在标记的函数中async
async function doThings() {
updateUI(event);
let userIsSignedIn = await ajaxCall(); // see below
nextThing(userIsSignedIn);
anotherThing();
moreThings();
}
并返回一个 PromiseajaxCall
(什么是syncCall
)
function ajaxCall(){
return $.ajax({
dataType: 'json',
type: 'GET',
url: '/calls/synccall'
}).then(json => json.is_signed_in);
}
通过转译器(如 babel)运行它以生成应在 Internet Exploder 和类似的“向后”浏览器上运行的代码
总结:最后你有两个选择
- 使用 async:false 并具有垃圾用户体验
- 拥抱异步并编写适合 21 世纪的代码