无法通过Cloud Functions(onCall)从Cloud Firestore返回一个json数组到Swift

问题描述 投票:0回答:1

从云函数中获取结果时遇到问题。

这是我的云功能:

exports.retrieveTrips = functions.https.onCall((data, context) => {
 const uidNumber = context.auth.uid;

 var arrayOfResults = new Array();

 var idOfFoundDoc;
 var query = admin.firestore().collection('Users').where('UID','==', uidNumber);
 query.get().then(snapshot => 
 {
     snapshot.forEach(documentSnapshot => 
     {
          idOfFoundDoc = documentSnapshot.id;
     });
     var queryDoc = admin.firestore().collection('Users').doc(idOfFoundDoc).collection('Trips');
     queryDoc.get().then(snapshot => 
     {
         snapshot.forEach(documentSnapshot => 
         {
             arrayOfResults.push(documentSnapshot.data());
         });
        console.log('ARRAY: ' , arrayOfResults);
        return arrayOfResults; 
     })
     .catch (err => 
     {
        console.log ('Error adding document: ', err);
     });

 })
 .catch (err => {

        //response.send('Error getting documents', err);
        console.log ('Error getting documents', err);
 });

这是我在我的应用程序中的代码。

    @IBAction func RetrieveTripsButton(_ sender: Any)
{

    self.functions.httpsCallable("retrieveTrips").call() {(result, error) in
        if let error = error as NSError? {
            if error.domain == FunctionsErrorDomain
            {
                let message = error.localizedDescription
                print ("Message: " + message)
            }
            return
        }

        print ("Result: -> \(type(of: result))")
        print("Result.data type: \(type(of: result?.data))");
        print ("Result.data -> \(result?.data)")
    }
}

这是打印结果。

Result: -> Optional<FIRHTTPSCallableResult>
Result.data type: Optional<Any>
Result.data -> Optional(<null>)

控制台日志能够正确打印arrayOfResults。此外,当我将此函数更改为onRequest并向其提供相关信息时,res.status(200).send(arrayOfResults)能够在页面中显示JSON数组。

如果我将return arrayOfResults;放在.then函数之外,我会得到一个结果以及一个空数组。我的问题类似于this problem here,但当我返回{ text: "some_data" };时,我甚至无法收到。

任何帮助都会很棒,谢谢!

swift firebase google-cloud-firestore swift4 google-cloud-functions
1个回答
0
投票

您必须链接不同的promise并返回promises链的结果,如下所示。

请注意,它实际上是OP在他提到的SO帖子的答案中解释的“问题是我忘记了从云函数返回实际的承诺”。

exports.retrieveTrips = functions.https.onCall((data, context) => {
 const uidNumber = context.auth.uid;

 const arrayOfResults = new Array();

 let idOfFoundDoc;
 const query = admin.firestore().collection('Users').where('UID','==', uidNumber);

 return query.get().then(snapshot => {  // here add return
     snapshot.forEach(documentSnapshot => 
     {
          idOfFoundDoc = documentSnapshot.id;
     });
     const queryDoc = admin.firestore().collection('Users').doc(idOfFoundDoc).collection('Trips');
     return queryDoc.get();   // here add return and chain with then()
 })
 .then(snapshot => {
         snapshot.forEach(documentSnapshot => {
             arrayOfResults.push(documentSnapshot.data());
         });
        console.log('ARRAY: ' , arrayOfResults);
        return { arrayOfResults : arrayOfResults }; //return an object

 })
 .catch (err => {
        console.log ('Error getting documents', err);
        //Here you may return an error as per the documentation https://firebase.google.com/docs/functions/callable#handle_errors, i.e. by throwing an instance of functions.https.HttpsError         
 });

});

我还建议您查看Firebase团队的这两个视频,关于云功能和承诺:https://www.youtube.com/watch?v=7IkUgCLr5oAhttps://www.youtube.com/watch?v=652XeeKNHSk

© www.soinside.com 2019 - 2024. All rights reserved.