【问题标题】:JAVASCRIPT unable to assign variables got from FIRESTORE - solved: few nested promisesJAVASCRIPT 无法分配从 FIRESTORE 获得的变量 - 已解决:嵌套承诺很少
【发布时间】:2020-06-12 10:07:04
【问题描述】:

Firestore 新手。试图尽可能清楚。无法分配从 fisetore DB 接收到的属性, 在js中找不到答案。

建立一个问答论坛,有 3 个集合:用户、消息、查询。 尝试添加查询(在创建 msg 和用户的有效文档并获得他们的 doc id 之后)。 打印到控制台时,工作正常但不更新数据库

当遇到与数字相同的问题时,尝试使用 parseInt 进行换行并且它有效,但 parseString 似乎不存在。 还尝试只声明变量而不用“”,但随后出现错误。

function DBaddNewQuery2(userID, firstMsgId) {
  let creatorFirstName =" ";
  let creatorLastName=" " ;
  let firstMsgText =" ";

  // get the user's first and last name
  db.collection("users").doc(userID).get().then(function(doc) {
    creatorFirstName = doc.data().firstName;
    creatorLastName= doc.data().lastName;
    console.log("creatorFirstName is ",creatorFirstName); // prints the right data!
    }).catch(function(error) {
    console.log("Error getting first and last name for user in addquery2:", error);
  });

  // get msg text
  db.collection("message").doc(firstMsgId).get().then(function(doc) {
    firstMsgText = doc.data().msgText;
    console.log("msg text is ",firstMsgText); // prints the right data!
    }).catch(function(error) {
    console.log("Error getting document:", error);
  });

  // generate query id
  let queryId = create_UUID();

  db.collection("query").doc(queryId).set({

    'creatorFirstName': creatorFirstName, //update db as " "
    'creatorLastName': creatorLastName,
    'firstMsgText': firstMsgText,

  }).then(function () {
    console.log("setDocument: query Document successfully written!, query id: ", queryId);
  })
    .catch(function (error) {
      console.error("setDocument: Error writing document: ", error);
    });

}

【问题讨论】:

  • 你是否试图连续运行一堆异步函数,而后续函数依赖于之前函数的数据?
  • 是的,如果不清楚,我很抱歉

标签: javascript database google-cloud-firestore


【解决方案1】:

1- async/await 可以在这里做点什么


    async function DBaddNewQuery2(userID, firstMsgId) {
      let creatorFirstName = ' ';
      let creatorLastName = ' ';
      let firstMsgText = ' ';

      // get the user's first and last name
      let userRef = await db
        .collection('users')
        .doc(userID)
        .get();

      creatorFirstName = userRef.data().firstName;
      creatorLastName = userRef.data().lastName;
      // get msg text
      let messageRef = await db
        .collection('message')
        .doc(firstMsgId)
        .get();

      firstMsgText = messageRef.data().msgText;

      // generate query id
      let queryId = create_UUID();

      db.collection('query')
        .doc(queryId)
        .set({
          creatorFirstName: creatorFirstName, //update db as " "
          creatorLastName: creatorLastName,
          firstMsgText: firstMsgText,
        })
        .then(function() {
          console.log(
            'setDocument: query Document successfully written!, query id: ',
            queryId,
          );
        })
        .catch(function(error) {
          console.error('setDocument: Error writing document: ', error);
        });
    }

2- 嵌套结构

function DBaddNewQuery2(userID, firstMsgId) {
  let creatorFirstName = ' ';
  let creatorLastName = ' ';
  let firstMsgText = ' ';

  // get the user's first and last name
  db.collection('users')
    .doc(userID)
    .get()
    .then(function(doc1) {
      creatorFirstName = doc1.data().firstName;
      creatorLastName = doc1.data().lastName;
      console.log('creatorFirstName is ', creatorFirstName); // prints the right data!

      // get msg text
      db.collection('message')
        .doc(firstMsgId)
        .get()
        .then(function(doc2) {
          firstMsgText = doc2.data().msgText;
          console.log('msg text is ', firstMsgText); // prints the right data!

          // generate query id
          let queryId = create_UUID();

          db.collection('query')
            .doc(queryId)
            .set({
              creatorFirstName: creatorFirstName, //update db as " "
              creatorLastName: creatorLastName,
              firstMsgText: firstMsgText,
            })
            .then(function() {
              console.log(
                'setDocument: query Document successfully written!, query id: ',
                queryId,
              );
            })
            .catch(function(error) {
              console.error('setDocument: Error writing document: ', error);
            });
        })
        .catch(function(error) {
          console.log('Error getting document:', error);
        });
    })
    .catch(function(error) {
      console.log(
        'Error getting first and last name for user in addquery2:',
        error,
      );
    });
}

【讨论】:

    【解决方案2】:

    这个解决方案对我有用,不仅像 @MUHAMMADILYAS 建议的那样嵌套,而且还使用 Promise.all

    谢谢!

    function DBaddNewQuery(userID, firstMsgId) {
    
      let creatorFirstName = " "; let creatorLastName = " "; let firstMsgText = " ";
      // generate query id
      let queryId = create_UUID();
    
      var userRef = db.collection("users").doc(userID);
      const promise1 = userRef.get();
      const promise2 = db.collection("message").doc(firstMsgId).get();
      Promise.all([promise1, promise2]).then((values) => {
        doc1 = values[0];
        doc2 = values[1];
        creatorFirstName = doc1.data().firstName;
        creatorLastName = doc1.data().lastName;
        firstMsgText = doc2.data().msgText;
    
        db.collection("query").doc(queryId).set({  // CREATE QUERY:
    
          'creatorFirstName': creatorFirstName, 
          'creatorLastName': creatorLastName,  
          'firstMsgText': firstMsgText,  
        }).then(function () {
          console.log("setDocument: query Document successfully written!");
        })
          .catch(function (error) {
            console.error("setDocument: Error writing document: ", error);
        });
    
      });
    
      return queryId;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 2017-04-04
      • 2019-05-09
      • 2014-09-25
      • 2022-12-14
      相关资源
      最近更新 更多