如果函数GetTest返回值,一切正常,否则出错。我怎样才能妥善处理空头承诺?我试过了,但我得到了:
无法加载资源:服务器响应状态为500(内部服务器错误)
getTest = function (testId)
{
var promise = $http(
{
method: 'POST',
url: self.baseUrl + 'Test/getTest',
contentType: 'application/json',
data: {
testId: testId
}
});
return promise;
}
[HttpPost]
public ActionResult getTest(string testId)
{
JsonResult jsonResult = new JsonResult();
try
{
Test model = new Test();
string returnValue = model.GetTest(Convert.ToInt32(testId));
if(!string.IsNullOrEmpty(returnValue))
{
jsonResult.Data = returnValue;
Response.StatusCode = 200;
return jsonResult;
}
else
{
Response.StatusCode = 500;
return Content("NoResult");
}
}
catch (Exception ex)
{
return jsonResult;
}
}
答案 0 :(得分:2)
您可以使用.then()
的第二个参数来处理失败的承诺:
getTest()
.then(
function (result) {
// handle result
},
function (error) {
// request failed with error
}
);