【问题标题】:how can I return values from chained deferreds in jQuery?如何从 jQuery 中的链式延迟返回值?
【发布时间】:2013-07-17 22:04:14
【问题描述】:

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

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

【问题讨论】:

  • A promise 只是应该为您提供对由 AJAX 调用或 $.Deferred() 调用创建的 deferred 对象的不可变引用。您可以在 promise 对象上运行 deferred._____() 函数以获取其状态或对其进行操作。烤的答案可能就是你要找的。另外,我认为作为deferred 处理程序传递的函数的第一个参数通常是延迟对象本身。
  • @roasted 的答案是将getMessage() 视为promise,如果我理解正确的话——但这只是一个简单的函数,所以我不能使用.then()——有没有办法定义一个作为延迟函数?
  • ajaxFetch 的返回值是什么?您是从$.ajax() 返回jqXHR 吗?处理这个deferred 的函数也应该期待(data, status, jqXHR) 参数。这有帮助吗?

标签: jquery jquery-deferred


【解决方案1】:

从中返回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
   });
}

【讨论】:

  • 当你可以只在处理程序本身中包装ajaxFetch() 时,似乎是多余的。
  • 是的,但我的getMessage() 不仅仅只是返回一个承诺。这就是为什么我试图将结果从getMessage() 传递回点击处理程序。
  • @tim 将 promise 存储在一个变量中并从 getMessage 返回一个对象,例如{ messagePromise: thePromise, otherReturn: "etc" }?
  • 我不知道 ajaxFetch() 方法是什么以及为什么要使用它,但通常,ajax 方法返回的 jqXHR 对象实现 promise 接口。我不知道你也这样实现它是什么意思。我所知道的是,console.log(someAjaxFunction()) 永远不会产生您似乎期望的结果
  • @tim 支持烤的评论在这里:api.jquery.com/jQuery.ajax/#jqXHR "从 jQuery 1.5 开始,$.ajax() 返回的 jqXHR 对象实现了 Promise 接口,为它们提供了所有属性、方法和行为承诺……”
【解决方案2】:

我不完全确定我理解你想要做什么,但如果你想在点击处理程序的上下文中使用延迟对象执行回调,你可以从 getMessage 返回 ajax 函数本身。尝试这样的事情:(未经测试)

$('#button').on('click', function(){
    getMessage(3).then(function(result) {
        // do success callback here
        console.log(result); // 'hello'
    }, function(result) {
        // do fail callback here
    });
});

function getMessage(id){
    return ajaxFetch(id);
};

【讨论】:

  • 是的,这是一种方式——但这不是我想要做的。我特别想避免点击处理程序中的任何逻辑。
  • 我不相信有任何方法可以将结果从服务器返回到点击处理程序。我能想到的唯一其他选择是将您的回调作为参数传递给 getMessage,例如getMessage(id, callback)。然后在 ajaxFetch 成功时你会做callback(result)
猜你喜欢
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
  • 2018-10-11
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
  • 2018-04-12
相关资源
最近更新 更多