2014-12-05 62 views
0
与多个嵌套。当

jQuery的AJAX没有返回正常。由于未定义的变量,获取错误“Uncaught SyntaxError:Unexpected token u”。带有多个嵌套的.when内部的jQuery ajax。返回undefined

下面是我的代码和流程。

此方法将上一个按钮,点击它在内部调用具有依赖性的多种方法的情况下调用。在下面的例子中,流量是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导致错误“Unexpected token u”。

我不知道我是否已经解释了我的查询清楚,但是如果需要的话,我可以在更详细的解释。

回答

1

您的代码没有显示任何异步操作,因此我们甚至无法帮助您使用实际的异步代码。这就是我们需要看到的,以帮助你。

有各种各样的问题:

  1. $.when()必须通过一个或多个承诺
  2. $.when()是没有必要的,如果你只有一个承诺,等待,你可以只是在使用.then()直接单一的承诺。
  3. buildAndroidApk()unlockAndroidKey()必须返回承诺
  4. 你试图返回测试JSON字符串中有语法错误(错误引用)
  5. 如果你使用jQuery和你是从你的服务器,让jQuery的JSON回来会自动为你解析它 - 你不需要手动解析它。

为了让您的代码按照结构化的方式工作,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; 
    }); 
} 
+0

只是为了理解目的我硬编码我的代码中的json字符串。其实我在PHP中使用数组构建json,并在JavaScript中进行JSON :: parse。你是对的,函数buildAndroidApk()没有返回promise。在我将$ return放在$之前后,现在它正在返回。 – Malaiselvan 2014-12-05 23:38:58

+1

@Malaiselvan - 你明白,当你只有一个承诺时,你不需要'.when()'。你可以直接在promise上使用'.then()'。 – jfriend00 2014-12-06 01:47:01

0

,我发现自己的答案。我在$ .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; 
    }); 
}