请查看我的代码。
var posts = PostsData.getPosts();
var postFunc = function(key) {
return posts[key];
}
$scope.$watch($scope.active, function() {
$timeout(function() {
var markers = [];
for (var key in posts) {
console.log(key);
var p = gf.get(key).then(function(location) {
var post = postFunc(key);
console.log(key);
return ({
idKey: key,
title: post.title,
coords: {
latitude: location[0],
longitude: location[1]
}
});
});
markers.push(p);
}
$q.all(markers).then(function(markers) {
$scope.markers = markers;
});
});
})
}
在循环中有两行" console.log(key)"。 第一个console.log打印数据的准确表示,这是唯一键。第二个console.log打印重复的相同数据,这是不准确的。我无法理解为什么会这样。
非常感谢您的帮助。
答案 0 :(得分:0)
从第二SQL> create table app as
2 with app (app_ver, num_subversions) as (
3 select 'A', 2 from dual union all
4 select 'B', 3 from dual union all
5 select 'C', 4 from dual
6 )
7 select app_ver, num_subversions
8 from app a;
Table created
SQL> with a1 (app_ver, num_subversions, lvl) as (
2 select app_ver, num_subversions, 1
3 from app
4 union all
5 select app.app_ver, app.num_subversions, a1.lvl + 1
6 from app, a1
7 where app.app_ver = a1.app_ver
8 and a1.lvl < app.num_subversions)
9 search depth first by app_ver, num_subversions set my_order
10 select app_ver || lvl
11 from a1;
APP_VER||LVL
-----------------------------------------
A1
A2
B1
B2
B3
C1
C2
C3
C4
9 rows selected
开始你有相同的价值是很正常的。原因是你的异步函数console.log(key)
。调用此函数时,循环已完成执行, gf.get(key).then(function(location) { .. }
的值是循环中的最后一个值。我不确定key
是做什么的,但如果gf.get
是一个数组,你可以通过递归帮助实现你的结果,如下所示
posts
注意:在此方法中,我们等待每个承诺得到解决,然后再转到下一个var posts = PostsData.getPosts();
var postFunc = function(key) {
return posts[key];
}
var markers = [];
var getMarkers(key) {
if (key > posts.length - 1) {
// promise resolved for each item in posts
$q.all(markers).then(function(markers) {
$scope.markers = markers;
}
return;
}
console.log(key);
gf.get(key).then(function(location) {
var post = postFunc(key);
console.log(key);
markers.push({
idKey: key,
title: post.title,
coords: {
latitude: location[0],
longitude: location[1]
}
});
getMarkers(++key);
});
}
$scope.$watch($scope.active, function() {
markers = [];
getMarkers(0);
});
答案 1 :(得分:0)
解决问题的另一种方法是使用IIFE闭包。
key
通过使用IIFE(Immediately Invoked Function Expression),每个.then
的值都会保留,直到 #pragma mark - Previewing delegate
- (UIViewController *)previewingContext:(id <UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
{
UIViewController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"detail"];
detailVC.preferredContentSize = CGSizeMake(0.0, 568.0);
previewingContext.sourceRect = self.btnDetail.frame;
return detailVC;
}
- (void)previewingContext:(id <UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit{
[self showViewController:viewControllerToCommit sender:self];
}
方法内的函数完成。