繁体   English   中英

如何从 firebase 函数返回 promise 和 object?

[英]How do i return a promise and object from firebase functions?

提醒一下,这是我使用云功能的第一天。 我有一个云 function 在验证一些详细信息后向我的客户返回 object。 我还想使用这个 function 写入我的 Firestore 数据库。 但是要写入我的数据库,我必须从我的 function 返回 promise。 我如何同时做到这一点并完成这项工作? 这是我的代码。

export const verifyDetails = functions.https.onCall(async (data, context) => {

    const chosenUsername = data.username;
    const chosenEmail = data.email;

    const allEmails: string[] = [];
    const allUsernames: string[] = [];

    let usernameExists = false;
    let emailExists = false;

    await admin.firestore().collection('Users').get()
        .then((snapshot) => {
            snapshot.forEach((doc) => {
                allEmails.push(doc.data().email);
                allUsernames.push(doc.data().username);
            })

            allEmails.forEach((email) => {
                if (email === chosenEmail) {
                    emailExists = true;
                }
            });

            allUsernames.forEach((username) => {
                if (username === chosenUsername) {
                    usernameExists = true;
                }
            });

            if (!usernameExists && !emailExists) {
                registerDetails(chosenUsername, chosenEmail);
            }

        })
        .catch((error) => {
            console.log('Error retrieving firestore documents', error);
        });

    return { usernameExists: usernameExists, emailExists: emailExists };

});


export const registerDetails = functions.https.onCall(async (data, context) => {
    return admin.firestore().collection('Users').add({
        email: data.chosenEmail,
        username: data.chosenUsername
    });
});

我尝试使用另一个 https 回调 function 并在主 function 中调用它。 这不会写入我的数据库,但会返回我的 object。 请帮忙!

registerDetails function 的内容分解出来,以便两个 onCall 函数都可以使用它...

async function addUser(data) {
  return admin.firestore().collection('Users').add({
    email: data.chosenEmail,
    username: data.chosenUsername
  })
}

现在verifyDetails可以像这样使用它......

export const verifyDetails = functions.https.onCall(async (data, context) => {
  let querySnapshot = await admin.firestore().collection('Users').get()
  // code from the OP here.
  // because we used await, the code doesn't have to be in a then block
  
  await addUser({ chosenEmail, chosenUsername })
  return { usernameExists: usernameExists, emailExists: emailExists };
})

并且registerDetails可以像这样使用它...

export const registerDetails = functions.https.onCall(async (data, context) => {
  return addUser(data)
})

请注意,verifyDetails 不会返回 promise,但它会等待异步工作,这也是有效的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM