这个函数返回空数组有什么理由吗?我通过调试器运行它并且for循环正在工作并且正在将用户附加到newUsers数组,但是当它完成并返回值时,它是空的。
func fetchUsers(ref:FIRDatabaseReference) -> [User] {
var newUsers = [User]()
ref.observeEventType(.Value, withBlock: {snapshot in
for user in snapshot.children {
let users = User(snapshot: user as! FIRDataSnapshot)
newUsers.append(users)
}
})
print("closure exited. There are \(newUsers.count) Users in newUsers")
return newUsers
}
答案 0 :(得分:0)
正如评论所说,你可能是异步运行循环。
无论如何,为了使它起作用,假设上述情况属实,你可能有几种不同的方法。
使函数简单地返回,并将完成处理程序作为其参数。如果这样做,在循环结束时,您可以运行完成处理程序。
如果您真的希望此功能同步工作,您可以使用expectationWithDescription和.fulfill()
答案 1 :(得分:0)
为了从Firebase获取数据,我通常会声明一个私有变量来存储结果,如下所示:
var request = require( "superagent" );
var PostUrl = browser.baseUrl + 'rest/1.0/dev/users';
var CreateTenantUrl = browser.baseUrl + 'rest/1.0/tenant';
exports.CreateTenant = function(body){
var data = '{' + body + '}';
request.post(CreateTenantUrl).set('Content-Type', 'application/json').set('serviceSharedSecret', 'sharedsecret').send(data).end(function(err,res){
if(err){
console.log("CreateTenant post error= ", err )
} else{
console.log("CreateTenant post response = ", res.status)
//Create user once tenant has been successfully created
Commons.CreateUsers('"userName": "test1", "tenantKey": "1", "password": "Test1", "userID": "1"');
}
expect(res.status).toEqual(200)
});
};
exports.CreateUsers = function(body){
var data = '{' +body + '}';
request.post( PostUrl ).set('Content-Type', 'application/json').send(data).end(function(err,res){
if(err){
console.log("CreateUsers post error= ", err )
} else{
console.log("CreateUsers post response = ", res.status)
}
expect(res.status).toEqual(202)
});
};
如果我理解您在函数中返回private users = [User]()
func fetchUsers(ref: FIRDatabaseReference) {
ref.observeEventType(.Value, withBlock: {snapshot in
for user in snapshot.children {
let _user = User(snapshot: user as! FIRDataSnapshot)
self.users.append(_user)
}
/*If I have a tableView associated with users as its dataSource then just reload the data*/
if self.users.count > 0 {
self.tableView.reloadData()
}
})
}
数组的要求,那么您将直接访问此user
属性的值(假设您在访问此属性之前已在某处调用此函数)。希望这会对你有所帮助。
答案 2 :(得分:0)
因为你在异步块中使用完成。试试这个
func fetchUsers(ref:FIRDatabaseReference, completion(users: [Users])) {
var newUsers = [User]()
ref.observeEventType(.Value, withBlock: {snapshot in
for user in snapshot.children {
let users = User(snapshot: user as! FIRDataSnapshot)
newUsers.append(users)
}
print("closure exited. There are \(newUsers.count) Users in newUsers")
completion(users: newUsers)
})
}