我正在尝试跟踪函数调用的返回值:
$('#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/