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

标签 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
});

下面的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
   });
}

如何让我的跟踪输出 'hello'

我认为...

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

最佳答案

返回promise接口(interface)和其中的代码逻辑:

 $('#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
   });
}

关于jquery - 如何从 jQuery 中的链式延迟返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17711077/

相关文章:

javascript - Reactjs组件的异步渲染

javascript - 当一组 deferred 中的一个失败时如何处理

asp.net - 使用 JQuery 在 GridView ASP.NET 中选择所有复选框

jquery - 'rejected' 对于 jqXHR 之外的延迟对象意味着什么?

javascript - 排队/节流 jQuery ajax 请求

javascript - JQuery如何获取可见区域的元素

javascript - 如何在 x 时间后无响应时取消 ajax 请求或第三方 js 请求 w/abort()

javascript - 这个幻灯片范围,当拖动到右端时,我想显示文本,例如 : unlimited, 我该怎么做?

javascript - 我想使用没有 iframe 或对象的外部 url 加载页面

javascript - 未选中返回盒子上的属性(property)