简体   繁体   English

如果 firestore doc.exists 我如何停止父 function 的执行?

[英]If firestore doc.exists how do I stop execution of parent function?

I'm trying to stop the async function if a username is found in the database.如果在数据库中找到用户名,我正在尝试停止异步 function。 I can find existingUsername = true, but handleSignup continues to execute and overwrites existing user data.我可以找到existingUsername = true,但handleSignup 继续执行并覆盖现有用户数据。

async function handleSignup {

    var docRef = db.collection("users").doc(username);
    var existingUsername = false

    docRef.get().then((doc) => {
        if (doc.exists) {
            existingUsername = true
        }
        else {
            existingUsername = false
        }
    })

    if (existingUsername == true) {
        return setError("Username exists") // How do I stop the function handleSignup?
    }

    }
//database code to create user
}

Probably best to use async await with this.可能最好使用async await

async function handleSignup() {

    const docRef = db.collection("users").doc(username);

    const doc = await docRef.get();

    if (doc.exists === true) {
        throw setError("Username exists")
    }

//database code to create user
}

The rest of the execution happens before the promise return because this is how javascript works.. you should use await or add another then chain.执行的 rest 发生在 promise 返回之前,因为这就是 javascript 的工作原理。您应该使用 await 或添加另一个 then 链。 i refactored your code to make it work using await:我重构了您的代码以使其使用等待工作:

 var existingUsername = false

 const doc = await docRef.get();
 const existingUsername = doc.exists();

 if (existingUsername) {
    return setError("Username exists")
 }

//database code to create user

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

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