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/

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#wireshark#的问题:并且能够给数据做标注,如这个流量是在看视频或者是在转账
  • ¥90 请问,这个视频播放软件的名称,用过的朋友请给答案,上方..avi是啥意思?是看短剧还是播放本地视频?
  • ¥15 运筹优化,gurobi,python
  • ¥15 基于python的电影系统推荐
  • ¥20 springmvc重定向和返回json
  • ¥15 数学建模——参会安排怎么做
  • ¥15 电脑键盘实现触摸功能
  • ¥25 matlab无法将表达式转换为双数组怎么解决?
  • ¥15 单片机汇编语言相关程序
  • ¥20 家用射频美容仪技术规格