[英]How can I make first Ajax Get request be finish before I call next one?
I have to methods, that return promises.我必须方法,即返回承诺。 And I want to make second method to be executed after first would get and manipulate data.
我想让第二个方法在第一个获取和操作数据之后执行。 This question has being asked several times, still cannot find a way to make it work.
这个问题已经被问了好几次了,仍然找不到让它工作的方法。 Here is my code:
这是我的代码:
self.getSpesialitet = function () { console.log("Starting Spesialitet"); return $.get(options.getSpesialitetUrl, { 'recno': recno }, function (data) { ////Code console.log("Success Spesialitet"); }); }; self.getVedtak = function () { console.log("Starting Vedtak"); return $.get(options.getVedtakUrl, { 'recno': recno }, function (data) { ////Code console.log("Success Vedtak"); }); }; $.when(self.getSpesialitet()).then(self.getVedtak()).then(console.log("Everything is done"));
And here is the result witch I get:这是我得到的结果女巫:
Starting Vedtak
Starting Spesialitet
Everything is done
Success Vedtak
Success Spesialitet
And the result I would like to get:我想得到的结果:
Starting Vedtak
Success Vedtak
Starting Spesialitet
Success Spesialitet
Everything is done
You can use success
calls in order to chain your functions, like this:您可以使用
success
调用来链接您的函数,如下所示:
self.getVedtak().success(function(){
self.getSpesialitet().success(function(){
console.log('Everything is done');
})
})
Please understand that $.get
, $.post
and $.ajax
calls are always asynchronous calls.请理解
$.get
、 $.post
和$.ajax
调用始终是异步调用。 It's like fire and forget.这就像火灾和忘记。 It doesn't wait until the execution is complete.
它不会等到执行完成。 To make your code work, you need to call your second method when the first method has returned.
为了使您的代码工作,您需要在第一个方法返回时调用第二个方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.