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文档.
返回 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)