异步Javascript函数,不返回值 [英] Async Javascript functions, not returning values
问题描述
我遇到一个困扰我的问题.基本上是这样的情况:
I'm having an issue that is burning my head. Basically this is the scenario:
我有一个 callController()
函数,只需使用 jQuery.load()
方法来加载控制器,加载后,我就可以玩返回参数.
I have a callController()
function, which just simple use the jQuery.load()
method to load a controller, after loaded, I can play with the returning parameters.
现在...在我的一个控制器中,我需要检查一个验证规则,以允许用户执行某些功能,但是,我创建了一个像这样的功能:
Now... in one of my controllers there is a validation rule I need to check in order to to allow the user to execute certain functionality, however, I create a function like this:
function myValRule() {
var val = callController('blablabla'),
response = "";
val.done(function(data) {
//my business logic
response = something;
}
return response;
}
如您所料, response
,即使它有一个值,它也会返回 undefined
,因此我设置了超时时间和 console.log()
它现在有一个值,但是即使将返回值放入 setTimeout()
中,我也无法返回该值.因此,基本上,当该方法调用此函数进行验证时,它会发现它为空.
As you imagine, response
, even if It has a value, it returns undefined
, so I set a timeout and console.log()
it and now it has a value, but I cannot make to return this value even if I put the return into the setTimeout()
. So basically when the method call this function to validate it finds it empty.
您能指出我解决这个问题的方向吗?
Can you point me on some direction to solve this issue?
推荐答案
请记住,这是异步的! return response;
早在实际调用 .done()
的时候就消失了.
Remember this is asynchronous! The return response;
is long gone by the time .done()
is actually called.
如果您需要以这种方式返回的值,请查看在您的 myValRule
函数中提供了一个回调函数(将从 .done()
内部调用)或是看看使用 $.Deferred
api,这样您就可以模仿 callController(...)
在做什么.
if you need the value returned in this fashion, look at either supplying a callback function in your myValRule
function (that would be called from within .done()
) or maybe look at using the $.Deferred
api so you can mimic what callController(...)
is doing.
这是这两种情况的示例(带有对 myValRule
的示例调用):
Here's an example of both scenarios (with example call to myValRule
):
function myValRule(callback){
var val = callController('blablabla'),
val.done(function(data){
var response = /* something */;
callback(response);
});
}
myValRule(function(response){
// here you have response
});
使用$ .Deferred
(我想是jQuery,因为有一个.done调用)
Using $.Deferred
(I assume it's jQuery since there's a .done call)
function myValRule(){
var df = $.Deferred(),
val = callController('blablabla');
val.done(function(data){
var response = /*something */;
df.resolve(response);
}).fail(df.reject);
return df.promise();
}
myValRule().done(function(response){
// here you have response
});
这篇关于异步Javascript函数,不返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!