简体   繁体   English

如何兑现空头承诺

[英]How to handle empty promises

If the function GetTest returns value everything works fine, otherwise errors out. 如果函数GetTest返回值,则一切正常,否则出错。 How can I properly handle empty promises? 我如何正确处理空缺承诺? I tried this but I got: 我尝试了一下,但是得到了:

Failed to load resource: the server responded with a status of 500 (Internal Server Error) 加载资源失败:服务器响应状态为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;
    }
}

You can handle failed promises by using the second argument of .then() : 您可以使用.then()的第二个参数来处理失败的承诺:

getTest()
    .then(
        function (result) {
            // handle result
        }, 
        function (error) {
            // request failed with error
        }
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM