Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度,函数回调的正确方式_Javascript_Angularjs_Function_Asynchronous - Fatal编程技术网

Javascript 角度,函数回调的正确方式

Javascript 角度,函数回调的正确方式,javascript,angularjs,function,asynchronous,Javascript,Angularjs,Function,Asynchronous,我正在用angular js为我的应用程序编写一个ItemProvider。 我选择了一项服务 app.factory('ItemProvider', function($http) { var url = "http://localhost:7888/api.php/json?"; return { get_data: function() { $http.get(url). success(function(data,stat

我正在用angular js为我的应用程序编写一个
ItemProvider
。 我选择了一项服务

app.factory('ItemProvider', function($http) {
  var url = "http://localhost:7888/api.php/json?";

  return {
    get_data: function() {          
      $http.get(url).
        success(function(data,status,headers,config) {
          json = data;
          console.log("app returned ok");
          console.log(json);
          callback(json);
        }).

        error(function(data,status,headers,config) {
          console.log("Error getting data from app!");
          json = data;
          callback(json);
        });

      callback = function(json) {
        console.log("callback");
        return json;
      }
      console.log("already done");
    }
  };
});
当然这里发生的事情是,
get_data
在通过
$http
返回到后端的实际调用之前立即返回


如何正确使用
get_data
函数从后端返回数据?我尝试添加一个回调(见上面的代码),但在调用它时,我意识到,
get_data
也已经完成了…

$http被硬编码为只能异步工作,这意味着您唯一的选择就是将其牢记在心。因此,get_data不可能直接返回数据,相反,它必须接受回调或返回承诺。在我看来,承诺路线要容易得多

用法示例:

//...
ItemProvider.get_data('/items')
  .success(function (items) {
    console.log(items);
  })
  .error(function () {...});
//...

“如何正确地使用get_data函数从后端返回数据?”这是不可能的
get_data
要么接受回调,要么返回承诺。我喜欢承诺解决方案!我有两个提供者,我将使用其中一个或另一个。我不想对接口做太多的更改,因此让Promise对我来说比添加回调看起来更优雅。Promise解决方案的另一个好处是,因为它是Promise,所以您可以使用
。然后
在从服务返回结果之前转换结果
.then(函数(结果){return transformResult(结果);})
。对于像
count
这样的方法来说,它非常好,因此您可以返回一个数字,而不是通常从rest api返回的带有count属性的对象。事实上,我很可能需要这个功能,因为我需要过滤这些数据!非常欢迎添加,谢谢!
//...
ItemProvider.get_data('/items')
  .success(function (items) {
    console.log(items);
  })
  .error(function () {...});
//...