我想调用一个回调函数,但由于调用错误而无法获取数据。
我尝试过:
//function with callback
filterList: function(type, cb) {
if (type == 'all') {
var resource = infoboxApi.resource1().query();
} else if (type == 'group') {
var resource = infoboxApi.resource2().query();
}
resource.$promise.then(function(events) {
var eventContainer = [];
angular.forEach(events, function(event) {
eventContainer.push({
id: event.id,
title: event.title
})
});
cb(eventContainer);
});
return wrapSaveHandlers(resource);
}
//call i tried
var newSources = [];
filterList('all', function(result) {
newSources = result;
});
我希望newSources包含数据,但如果我这样称呼它,则为空。
有人知道怎么称呼它吗?
答案 0 :(得分:1)
避免在基于承诺的API中使用回调。而是使用return语句:
//function without callback
filterList: function(type) {
var resource;
if (type == 'all') {
resource = infoboxApi.resource1().query();
} else if (type == 'group') {
resource = infoboxApi.resource2().query();
};
//RETURN the promise
return resource.$promise.then(function(events) {
var eventContainer = [];
angular.forEach(events, function(event) {
eventContainer.push({
id: event.id,
title: event.title
})
});
//RETURN the data
return eventContainer;
});
}
然后从返回的promise中提取数据:
var newSources = [];
filterList('all').then(function(result) {
newSources = result;
});
.then
方法返回一个新的诺言,该诺言通过successCallback
errorCallback
的返回值来解决或拒绝(除非该值是一个诺言,在这种情况下,它将被解决并使用promise chaining在该承诺中解析的值。