为什么.then不是函数? [英] Why .then is not a function?
问题描述
service.js
.factory('EventService', function ($http, $cordovaSQLite) {
return {
//some code here..
populateData: function (data) {
var items = [];
for (i = 0; i < data.length; i++) {
items.push(data[i]);
}
return items;
}
}
})
controller.js
.controller('NearCtrl', function ($scope, $http, $cordovaSQLite, EventService) {
EventService.getDataFromDB().then(function (result) {
if (result.length > 0) {
EventService.populateData(result).then(function (items) {
$scope.items = items;
})
} else {
EventService.getDataFromApi().then(function () {
EventService.getDataFromDB().then(function (result) {
EventService.populateData(result).then(function (items) {
$scope.items = items;
})
})
})
}
});
})
当我尝试运行此代码时,出现"TypeError:EventService.populateData(...).然后不是函数".
我在做什么错?谢谢.
该服务需要返回承诺,而不返回项目
populateData: function(data) {
var deferred = $q.defer();
var items = [];
for (i = 0; i < data.length; i++) {
items.push(data[i]);
}
deferred.resolve(items);
return deferred.promise;
}
尽管您可能会这样做,但您可能并不需要
var items = EventService.populateData(result);
//Do something with items here
通常在您异步执行某些操作时使用promises.就像调用API并等待响应一样.在这些情况下,响应可能需要几秒钟才能完成,然后调用.then函数.在您的情况下,如果您将该函数作为一个承诺,它将几乎立即被调用
这是$ q文档 AngularJS:API:$ q
service.js
.factory('EventService', function ($http, $cordovaSQLite) {
return {
//some code here..
populateData: function (data) {
var items = [];
for (i = 0; i < data.length; i++) {
items.push(data[i]);
}
return items;
}
}
})
controller.js
.controller('NearCtrl', function ($scope, $http, $cordovaSQLite, EventService) {
EventService.getDataFromDB().then(function (result) {
if (result.length > 0) {
EventService.populateData(result).then(function (items) {
$scope.items = items;
})
} else {
EventService.getDataFromApi().then(function () {
EventService.getDataFromDB().then(function (result) {
EventService.populateData(result).then(function (items) {
$scope.items = items;
})
})
})
}
});
})
When I'm trying to run this code, I get "TypeError: EventService.populateData(...).then is not a function".
What am I doing wrong ? Thanks.
that service needs to return a promise, not returning the items
populateData: function(data) {
var deferred = $q.defer();
var items = [];
for (i = 0; i < data.length; i++) {
items.push(data[i]);
}
deferred.resolve(items);
return deferred.promise;
}
you might not need this though since you could do
var items = EventService.populateData(result);
//Do something with items here
usually promises are used if you're doing something asynchronously. Like calling an API and waiting for a response. In those cases, the response might take seconds to finish THEN the .then function gets called. in your case if you make that function a promise it will be called almost immediately
EDIT: Here's the link to $q Documentation AngularJS: API: $q
这篇关于为什么.then不是函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!