[英]Return functions in Unity with Firebase Async Query
我試圖在 Firebase Firestore 中獲取用戶數據,因此我將 UID 傳遞給方法,它返回一個字符串(這是我的信息,比如我的用戶名)。 問題是firebase的查詢是Async的,導致查詢未完成就返回了。
當查詢完成時,我將如何工作以始終返回?
public string ReturnUserInfo(string _info, string _key)
{
string returnableValue = "";
Query userQuery = DB.Collection("users").WhereEqualTo("userID", _key);
userQuery.GetSnapshotAsync().ContinueWithOnMainThread(task =>
{
QuerySnapshot snapshot = task.Result;
foreach (DocumentSnapshot documentSnapshot in snapshot.Documents)
{
Dictionary<string, object> user = documentSnapshot.ToDictionary();
foreach (KeyValuePair<string, object> pair in user)
{
if (pair.Key == _info)
returnableValue = pair.Value.ToString();
}
};
});
return returnableValue;
}
你不能直接退貨!
該任務是異步執行的,您直接返回""
,因為您的方法會立即繼續執行代碼的 rest,而ContinueWithOnMainThread
會在任務完成后執行。
您需要稍微重新考慮一下,而是使用例如回調之類的
// pass in a callback to be executed when the information is successfully retrieved
public void ReturnUserInfo(string _info, string _key, Action<string> onSuccess)
{
var userQuery = DB.Collection("users").WhereEqualTo("userID", _key);
userQuery.GetSnapshotAsync().ContinueWithOnMainThread(task =>
{
var snapshot = task.Result;
foreach (DocumentSnapshot documentSnapshot in snapshot.Documents)
{
var user = documentSnapshot.ToDictionary();
// This is btw way better than iterating through the dictionary
if(user.TryGetValue(_info, out var value))
{
// invoke the callback
onSuccess?.Invoke(value.ToString());
// since you are also probably looking for only one result
return;
}
};
});
}
所以而不是使用例如
var result = ReturnUserInfo("xy", "zw");
你寧願做
ReturnUserInfo("xy", "zw", result =>
{
// use result here
});
或者用一個方法代替 lambda
ReturnUserInfo("xy", "zw", OnUserInfoReceived);
...
private void OnUserInfoReceived(string result)
{
// use result here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.