好的,函数返回值总是返回“ undefined”的问题
这是我的代码:
//called here:
var res = comms(GENSET_SN);
//the function
function comms(genserial) {
var Result;
//Webservice called here
MyServices.getCommsState(genserial, "S1", OnComplete1);
function OnComplete1(args) {
var Res = eval("(" + args + ")");
if (Res == 1) {
Result = 1;
} else {
Result = 0;
}
}
return Result;
}
请帮忙!!
最佳答案
我猜MyServices.getCommsState(genserial, "S1", OnComplete1);
是ajax请求吗?
如果是这样,将在Result
回调中实际设置OnComplete1
之前返回undefined
的值。
您将需要传递一个回调函数,该函数包含将使用Result
值的代码。
您可以更改代码来执行此操作,请注意,您将函数传递给comms,然后在OnComplete1
中调用它:
comms(GENSET_SN, function(res) {
// do whatever you need with res here!
});
//the function
function comms(genserial, callback) {
//Webservice called here
MyServices.getCommsState(genserial, "S1", function(args) {
var Res = eval("(" + args + ")"); // I would change this aswell, dont use eval!
callback(Res == 1 ? 1 : 0);
});
}