为什么这个函数没有返回任何东西?

问题描述:

我试图调试一些测试 - 我有以下代码:为什么这个函数没有返回任何东西?

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

使用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回调来解决它,然后调用者可以实现。

您应该从successerror处理

这里需要解决的几件事情调用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); 
    } 
},