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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)