如何从jQuery中的链式延迟返回值?

tim*_*tim 6 jquery jquery-deferred

我正在尝试跟踪函数调用的返回值:

$('#button').on('click', function(){
   console.log( getMessage(3) ); // I'm trying to get this to "hang" until ajax-related stuff is finished below
});
Run Code Online (Sandbox Code Playgroud)

ajaxFetch()下面的是一个通用的ajax处理程序返回预期的AJAX延迟对象.我们假设它是一个字符串值:'hello'.服务器响应是几秒钟.

function getMessage(id){
   ajaxFetch(id).done(function(result){
      // ... more stuff happening, but not relevant
   }).then(function(result){
      return (result); // I thought this would return to the click handler
   });
}
Run Code Online (Sandbox Code Playgroud)

如何获得输出的跟踪'hello'

我认为...

... console.log()需要以某种方式设置为a,promise但我很难理解jQuery文档.

A. *_*lff 5

返回 Promise 接口和其中的代码逻辑:

 $('#button').on('click', function(){
        $.when(getMessage(3)).then(function(result){console.log(result)});
    });

function getMessage(id){
   return ajaxFetch(id).done(function(result){
      // ... more stuff happening, but not relevant
   }).then(function(result){
      return result; //needed, otherwise it will return the object, not the result
   });
}
Run Code Online (Sandbox Code Playgroud)

  • 我不知道什么是 ajaxFetch() 方法以及为什么使用它,但通常,ajax 方法返回的 jqXHR 对象实现 Promise 接口。我也不知道你所说的实现它是什么意思。我所知道的是 console.log(someAjaxFunction()) 永远不会产生您似乎期望的结果 (2认同)