weixin_33714884 2015-01-16 16:59 采纳率: 0%
浏览 19

延迟javascript流程[重复]

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-01-16 17:04:31Z" class="relativetime">5 years ago</span>.</div>
        </div>
    </aside>

I'm working in javascript and AJAX. I make a call to a server to log in. It sends a response that the login was true. Then I need to collect all the information about the user by making a call to the server again. If I make the call immediately, the server will send back a response that the user is not logged in. I can use either setTimeout(myFunction(), 1000) or setInterval(myFunction(), 1000); to make the second call. I was wondering, is there a clean way to wait for the proper response before continuing without the rest of the code running? I guess my biggest question would be, how could I do this without putting everything in the callback response? I want the code to be somewhat modular.

</div>
  • 写回答

1条回答 默认 最新

  • weixin_33714884 2015-01-16 17:03
    关注

    You need to program using asynchronous techniques. A typical Ajax call in jQuery and then processing the response would look like this:

    $.ajax(...).then(function(result) {
       // put code here that uses the result 
       // then continue on with other code that should run after the result was processed
    });
    
    // code here will run BEFORE the ajax call completes
    

    If you want to run one ajax call and then another one after that, you can either chain them or you can run the second from within the completion callback of the first:

    $.ajax(...).then(function(result) {
         // process result of the first
    
         // run second ajax call
         return $.ajax(...)
    
    }).then(function(secondResult) {
         // code here when second ajax call is done
    });
    
    评论

报告相同问题?

悬赏问题

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