javascript - 返回结果给父函数

标签 javascript angularjs asynchronous

我一直在扯头发。我正在使用 ion-autocomplete 并希望通过工厂提取数据。

我的工厂......

myApp.factory('items', function($http){
   return {
      list: function(query,callback){
        $http.get('http://192.168.100.100/myApp/products/' + query).success(callback)
        }
        };
        });

为了获取我使用的数据..

   items.list(function(items) {
      $scope.items = items;
    });

自动完成请求数据的演示,如..

  $scope.getTestItems = function (query) {
                    return {
                        items: [
                            {id: "1", name: query + "1", view: "view: " + query + "1"},
                            {id: "2", name: query + "2", view: "view: " + query + "2"},
                            {id: "3", name: query + "3", view: "view: " + query + "3"}]
                    };
                };

所以我认为这是一个可行的解决方案..

   $scope.getTestItems = items.list(query,function(items)
        {   
        console.log(items);
        return items;
        }
        )

但显然不是。我试过了..

   $scope.getTestItems = function(query)
   {
   items.list(query,function(items)
        {   
        console.log(items);
        return items;
        }
        )
    }

它确实给了我一个结果的控制台,但它没有返回到 getTestItems

最佳答案

根据 the docs (假设我在这里有正确的库),你可以返回一个 promise

myApp.factory('items', function($http){
    return {
        list: function(query) {
            return $http.get(... + query).then(function(res) {
                return res.data; // unwrap the response data
                // see the "Returns" section at https://docs.angularjs.org/api/ng/service/$http#usage
            });
        }
    };
});

和 Controller

$scope.getTestItems = function(query) {
    return items.list(query);
};

关于javascript - 返回结果给父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31667526/

相关文章:

javascript - 如何根据 AngularJS 中的子结果集对结果进行排序

html - Bootstrap Popover 全屏带边距

api - 在 node.js 中管理基于命令的 TCP 套接字 API 上的连接

node.js - 多个异步写入 Node 中的同一文件

javascript - 调用函数而不将其结果分配给变量

angularjs - textAngular 标题按钮不能更大?

javascript - Vue.js browserify 找不到模块

python - 生成器函数和异步生成器函数的用途有什么区别

javascript - 如何在遇到屏幕边缘时停止 CSS 动画?

javascript - 如何动态调整 div 网格的大小以填充(但不超过)容器 div 的尺寸?