【发布时间】: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)参数。这有帮助吗?