我正在嘗試在 Firebase Firestore 中獲取用戶資料,因此我將 UID 傳遞給該方法,它回傳一個字串(這是我的資訊,如我的用戶名)。問題是firebase的查詢是異步的,導致查詢未完成就回傳。
查詢完成后如何始終回傳?
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;
}
uj5u.com熱心網友回復:
不能直接退貨!
該任務是異步執行的,并且您直接回傳"",因為您的方法會立即繼續執行其余代碼,而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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/430016.html
