同步ajax调用之前未显示更新的UI [英] updated UI not showing before sync ajax call

查看:57
本文介绍了同步ajax调用之前未显示更新的UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个JavaScript函数,它们相互调用.就像下面一样.

I Have a 2 JavaScript functions what call one after another. like following.

updateUI(event);
syncCall();

function updateUI(event) {
  formSubmitBtn = $(event.target).find('[type=submit]:not(".disabled")');
  formSubmitBtn.attr('disabled', 'disabled');
  var loadingText = I18n.t('Submitting');
  formSubmitBtn.val(loadingText).text(loadingText);
}

function syncCall(){
$.ajax({
    async: false,
    dataType: 'json',
    type: 'GET',
    url: '/calls/synccall',
    success: function (json) {
      userIsSignedIn = json.is_signed_in;
    }
  });
}

我要在同步ajax调用之前更新UI元素.但未显示用户界面更改.当我尝试调试代码时,效果很好.

I am updating a UI element before sync ajax call. but UI changes are not showing. When I try to debug the code it works fine.

推荐答案

我可以想象您的代码正在做类似的事情

I can imagine your code is doing something like

var userIsSignedIn;
updateUI(event);
syncCall();
nextThing(userIsSignedIn);
anotherThing();
moreThings();

对syncCall进行简单的更改-称为asyncCall不会混淆

With a simple change to syncCall - called asyncCall to be not confusing

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;

只需进行很小的更改即可改善最终用户的体验

Really a small change for improved end user experience

第二种选择是将您提供的所有代码包装在标记为async

a second alternative is to wrap all the code you presented in a function tagged async

async function doThings() {
    updateUI(event);
    let userIsSignedIn = await ajaxCall(); // see below
    nextThing(userIsSignedIn);
    anotherThing();
    moreThings();
}

并从ajaxCall返回承诺(syncCall)

function ajaxCall(){
    return $.ajax({
        dataType: 'json',
        type: 'GET',
        url: '/calls/synccall'
    }).then(json => json.is_signed_in);
}

通过编译器(如babel)运行此代码,以生成应可在Internet Exploder和类似后退"浏览器上运行的代码

Run this through a transpiler (like babel) to produce code that should work on Internet Exploder and similarly "backward" browsers

摘要:最后,您有两种选择

Summary: In the end you have two choices

  • 使用async:false并具有垃圾用户体验
  • 拥抱异步并编写适合21世纪的代码

这篇关于同步ajax调用之前未显示更新的UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆