简体   繁体   English

函数返回undefined而不是Boolean

[英]Function returns undefined instead of Boolean

I have a function that checks if the provided link is reachable, and it returns a Boolean value. 我有一个检查提供的链接是否可达的函数,它返回一个布尔值。

$scope.isReachable = function(uri) {
    var url = 'http://example.com/file.pdf';

    $http({
      method: 'GET',
      url: url
     })
     .success(function(data, status, headers, config) {
      console.log("I See it");
      return true;
    })
     .error(function(data, status, headers, config) {
      console.log("I don't");
      return false;
     });
  };

I have done a lot of functions and the return statements are fine, but this one. 我已经完成了很多功能,并且return语句还可以,但是这一项。 I don't know why but it seems very odd to me. 我不知道为什么,但是对我来说似乎很奇怪。 I'm not quite sure if it's the $http function, but it shouldn't matter, right? 我不太确定这是否是$ http函数,但这没关系,对吧? I can see the console messages but the boolean value. 我可以看到控制台消息,但布尔值。

Those return statements are returning inside the functions they belong to, which are the anonymous functions passed to success and error . 这些return语句正在它们所属的函数内部返回,这些函数是传递给successerror的匿名函数。

The isReachable function does NOT return any value. isReachable函数不返回任何值。 What it does is simply perform the request and pass it two callbacks. 它所做的只是简单地执行请求,并向其传递两个回调。

I don't have context of the rest of the code, but this is async programming and you are doing a request and passing callbacks. 我没有其余代码的上下文,但这是异步编程,您正在执行请求并传递回调。 The best way to go here in my opinion is passing the callbacks to the isReachable function like this: 我认为最好的方法是将回调传递给isReachable函数,如下所示:

var isReachableCallback = function(data, status, headers, config) {
  console.log("I See it");
  return true;
};

var isNotReachableCallback = function(data, status, headers, config) {
  console.log("I don't");
  return false;
};

$scope.isReachable = function(uri, isReachableCallback, isNotReachableCallback) {
    var url = 'http://example.com/file.pdf';

   return $http({
      method: 'GET',
      url: url
     })
     .success(isReachableCallback)
     .error(isNotReachableCallback);
  };

Not sure if these are best practices in Angular world though, I'm just trying to illustrate what's going on with the example. 虽然不确定这些是否是Angular世界中的最佳实践,但我只是想说明示例的情况。

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

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