JQuery $.post in a function. Wait for callback to define the return. [duplicate]

 ̄綄美尐妖づ 提交于 2019-12-13 23:17:05

问题


How would I, using $.post() in a function, force the return on the post callback?

Example:

function myFunction(){
   $.post(postURL,mydata,function(data){
      return data; 
   });
}

I have tried playing around with it using .done() and .queue() however neither has worked for me. I understand there is a fundamental flaw in my example; with that said, how can I achieve my desired functionality?


回答1:


This is impossible. $.Ajax calls will always return immediately. You need to deal with the return when it is called through a callback (possibly several seconds later). Javascript never blocks for a given call. It may help to think of your code like this:

 //This entirely unrelated function will get called when the Ajax request completes
 var whenItsDone = function(data) {
   console.log("Got data " + data); //use the data to manipulate the page or other variables
   return data; //the return here won't be utilized
 }

 function myFunction(){
   $.post(postURL, mydata, whenItsDone);
 }

If you're interested more on the benefits (and drawbacks) of Javascript's no-blocking, only callbacks: this Node.js presentation discusses its merits in excruciating detail.




回答2:


function myFunction(){
   var deferred = new $.Deferred();

   var request = $.ajax({
      url: postURL,
      data: mydata
   });

   // These can simply be chained to the previous line: $.ajax().done().fail()
   request.done(function(data){ deferred.resolve(data) });
   request.fail(function(){ deferred.reject.apply(deferred, arguments) });

   // Return a Promise which we'll resolve after we get the async AJAX response.
   return deferred.promise();
}


来源:https://stackoverflow.com/questions/6877318/jquery-post-in-a-function-wait-for-callback-to-define-the-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!