带有多个嵌套jQuery的.when不能正确返回。由于未定义变量而获得错误"Uncaught :意外令牌u“。
下面是我的代码和流程。
将在按钮单击事件中调用此方法,该按钮在内部调用具有依赖关系的多个方法。在下面的示例中,流是masterProcess->buildAndroidApk->unlockAndroidKey
function masterProcess(thisForm){
$.when(buildAndroidApk()).then(function(result){
obj = JSON.parse(result);
});
}
function buildAndroidApk(){
$.when(unlockAndroidKey()).then(function(result){
obj = JSON.parse(result);
//There are some other .when based on the obj response
return result;
});
}
function unlockAndroidKey(){
//this function connects to server via jQuery Ajax and gets a json string inside success or error block
return '{"success":"1","message":"","content":null}';
}
函数unlockAndroidKey获得json字符串,我可以在buildAndroidApk中接收该字符串。但是masterProcess正在接收一个未定义的字符串,JSON.parse会导致错误“意外令牌u”。
我不知道我是否清楚地解释了我的问题,但如果需要,我可以更详细地解释。
发布于 2014-12-05 23:17:36
您的代码没有显示任何异步操作,因此我们甚至无法帮助您完成实际的异步代码。这就是我们需要看到的,以帮助你。
各种问题:
$.when()
必须通过一个或多个承诺$.when()
,因为您可以直接在单个承诺上使用.then()
。buildAndroidApk()
和unlockAndroidKey()
必须兑现承诺要使代码按照结构化的方式工作,buildAndroidApk()
和unlockAndroidKey()
都必须返回承诺。现在,在这两个函数中,您都没有显示出承诺的返回。因此,当您尝试对返回值使用.then()
时,它将无法工作。或者,当您试图将其传递给$.when()
时,没有承诺要等待。
$.when()
需要将一个或多个承诺传递给它。您的buildAndroidApk()
方法不返回承诺,因此您将未定义的消息传递给$.when()
,因此在调用其.then()
处理程序之前,它没有等待的承诺。
此外,除非您有多个承诺,否则没有理由使用$.when()
。
您并没有向我们展示代码的实际异步部分,因此向您展示如何实际修复代码有点困难,但总体思路如下:
function masterProcess(thisForm){
buildAndroidApk().then(function(result){
obj = JSON.parse(result);
// use obj here
});
}
function buildAndroidApk(){
return unlockAndroidKey().then(function(result){
obj = JSON.parse(result);
//There are some other .when based on the obj response
return result;
});
}
function unlockAndroidKey(){
//this function connects to server via jQuery Ajax and gets a json string inside success or error block
return $.ajax(...).then(function(data) {
return something;
});
}
发布于 2014-12-05 23:16:59
我自己找到了答案。我把返回放在$.when之前,它运行得很好。
function buildAndroidApk(){
return $.when(unlockAndroidKey()).then(function(result){
obj = JSON.parse(result);
//There are some other .when based on the obj response
return result;
});
}
https://stackoverflow.com/questions/27326188
复制相似问题