2013-03-17 117 views
0

我試圖調試一些測試 - 我有以下代碼:爲什麼這個函數沒有返回任何東西?

test('Can get the test Side', 
     function() { 
      stop(); 
      debugger; 
      var result = getTestSide(); 
      debugger; 
      changeTestSide(result); 
     } 
    ); 


    // Step 1: Get test side 
    function getTestSide() { 
     $.ajax({ 
      type: 'GET', 
      url: urlWithId, 
      success: function (result) { 
       return "test success"; 
       debugger; 
       ok(true, "GET succeeded."); 
       if (!result.SideId === testSideId) { 
        throw "GET result does not equal testSideId"; 
       } else { 
        ok(true, "Returned key matches testSide Id."); 
        return result; 
       } 
      }, 
      error: function (result) { 
       return "test failure"; 
       debugger; 
       throw "Error"; 
      } 
     }); 
    }; 

無論怎樣,在頂部方法「結果」始終是不確定的。爲什麼是這樣?無論getTestSide成功還是失敗,我都會返回一個字符串。

+3

您的ajax調用是異步的,因此從「成功」或「錯誤」函數返回值不會影響任何內容。您不能在異步系統中以這種方式構建代碼。 – Pointy 2013-03-17 18:45:37

回答

0

使用return只從函數嵌套function回報裏面。你的代碼必須有不同的結構來獲得你想要的效果。這樣做的一種方式是通過一個回調函數到getTestSide將處理的反應,就像這樣:

test('Can get the test Side', 
    function() { 
     stop(); 
     debugger; 
     getTestSide(function (result) { 
      changeTestSide(result); 
     }); 
    } 
); 


// Step 1: Get test side 
function getTestSide(cb) { 
    $.ajax({ 
     type: 'GET', 
     url: urlWithId, 
     success: function (result) { 
      // removed this because it stops the rest from running 
      // return "test success"; 
      ok(true, "GET succeeded."); 
      if (!result.SideId === testSideId) { 
       throw "GET result does not equal testSideId"; 
      } else { 
       ok(true, "Returned key matches testSide Id."); 
       // Call the callback instead of returning. 
       cb(result); 
      } 
     }, 
     error: function (result) { 
      // removed this because it stops the rest from running 
      // return "test failure"; 
      debugger; 
      throw "Error"; 
     } 
    }); 
}; 

你也用throw你的成功和錯誤回調中;這些也不會做我認爲你期望他們做的事情,因爲在這些函數運行的時候,你的測試函數已經返回了,所以你沒有辦法讓這些異常發生。您的代碼無論如何都沒有顯示任何嘗試去捕捉異常,所以我沒有試圖解決這個問題,但您可以通過遵循與$.ajax函數類似的模式並提供successerror回調來解決它,然後調用者可以實現。

0

這裏需要解決的幾件事情調用changeTestSide方法:

success: function (result) { 
    return "test success"; 
    debugger; 
    ok(true, "GET succeeded."); 
    if (!result.SideId === testSideId) { 
     throw "GET result does not equal testSideId"; 
    } else { 
     ok(true, "Returned key matches testSide Id."); 
     return result; 
    } 
}, 

首先,你需要在你的AJAX調用changeTestSide(result);success功能。這是因爲AJAX默認爲異步調用,這意味着您的JavaScript不會等待getTestSide()完成執行,然後繼續執行test函數。其次,在你的success函數中,你所做的第一件事是return "test success";這將使函數返回,並且下面的代碼都沒有實際運行。這裏是你的代碼需要像什麼更好的例子:

success: function (result) { 
    debugger; 
    ok(true, "GET succeeded."); 
    if (!result.SideId === testSideId) { 
     throw "GET result does not equal testSideId"; 
    } else { 
     ok(true, "Returned key matches testSide Id."); 
     changeTestSide(result); 
    } 
}, 
相關問題