一旦用戶注冊,我希望能夠使用用戶 ID 創建一個檔案我發現這樣做的最佳位置,因為它只發生一次是當用戶注冊時這里的問題是它是一個等待功能我得到用戶ID的唯一地方是然后回呼任何想法如何語法這個..
const Signup = (email: string, password: string) => {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
const docRef = doc(db, 'clients', user.uid);
const payload = { clients: [] };
async () => await setDoc(docRef, payload);
// ...
})
.catch((error) => {
const errorCode = error.code;
//const errorMessage = error.message;
console.log(errorCode);
if (errorCode === 'auth/weak-password') {
_miscContext.SetSnackBarMsg(true, 'password must be at least 6 charechters');
}
if (errorCode === 'auth/email-already-in-use') {
_miscContext.SetSnackBarMsg(true, 'email already exists');
}
});
};
uj5u.com熱心網友回復:
.catch和方法的想法.then是回傳另一個可以鏈接的 Promise。
您可以從回呼中回傳它。如果函式的回傳型別.then是 a Promise,它將被忽略,否則,它將被轉換為 Promise,這就是為什么你可以鏈接.then和.catch方法
另外,這個問題:我應該總是使用 asych / await:
讓我們了解正在做什么async和await關鍵字(您需要了解這一點,您將了解在何處以及為什么需要使用它們)。
async- 這只是將您的函式轉換為異步函式(您可以添加async到您的函式并將其更改為 Promsie`
這是一個簡單的例子
function example() { return 1; }
console.log(example()); // log: 1
與異步
async function example() { return 1; }
console.log(example()); // log: Promise {<fulfilled>: 1}
// so if the async function is just converting your function to the promise, it means you can get the value by `.then` and `.catch` methods
await- 僅使用內部async函式,并等待 Promise 完成并將 Promise 轉換為回應
// 只是一個虛擬的例子
async function example() {
const responseOfPromise = await Promise.resolve(3);
return responseOfPromise;
}
您的實際功能的使用示例
const Signup = (email: string, password: string) => {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
const docRef = doc(db, 'clients', user.uid);
const payload = { clients: [] };
return setDoc(docRef, payload)
})
.then((responseOfSetDocFunction) => {
// and here the callback argument will be returned value from previous then (returned value of setDoc function)
console.log(responseOfSetDocFunction);
})
.catch((error) => {
const errorCode = error.code;
//const errorMessage = error.message;
console.log(errorCode);
if (errorCode === 'auth/weak-password') {
_miscContext.SetSnackBarMsg(true, 'password must be at least 6 charechters');
}
if (errorCode === 'auth/email-already-in-use') {
_miscContext.SetSnackBarMsg(true, 'email already exists');
}
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/429995.html
