weixin_33743661 2015-03-14 03:11 采纳率: 0%
浏览 42

jQuery AJAX竞争条件[重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call" dir="ltr">How do I return the response from an asynchronous call?</a>
                            <span class="question-originals-answer-count">
                                (38 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2015-03-14 04:25:21Z" class="relativetime">5 years ago</span>.</div>
        </div>
    </aside>

I've seen similar questions asked on SO but no quite my problem.

I have something like

var x = 5;
if( some condition ){
    $.ajax({
        url:"...",
        success: function(response){
            x = response.x;
        }
    }
}
some other logic
use x variable

What is happening is the thread executing the JS gets to the logic that uses x before the asynchronous task comes back.

Normally I would just put whatever logic inside the success function but I need the logic to happen regardless of whether or not the condition is met and I don't want to replicate code. Anyone have any suggestions? Should I just async to be false?

Thanks!

</div>
  • 写回答

3条回答 默认 最新

  • 零零乙 2015-03-14 03:34
    关注

    JQuery also has an fail() callback in case the Ajax fails. I'd just put the logic in both cases. (abstracted into a function) Check out this question.

    jQuery: Handle fallback for failed AJAX Request

    **Revision

    $.ajax's complete() method runs after an ajax call no matter what. Sounds perfect. http://api.jquery.com/jquery.ajax/

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!