如何在回调中使用等待?

how to use await inside then callback?

我希望能够在用户注册后使用用户 ID 创建文档我发现最好的地方是执行此操作,因为它只发生一次,即用户注册时,这里的问题是这是一个 await 函数,我唯一获得用户 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');
        }
      });
  };

.catch.then 方法的想法是 return 另一个可以链接的 Promise。

您可以 return 从回调中获取它。如果 .then 函数的 returned 类型是 Promise 它将被忽略,否则它将被转换为 Promise,所以这就是为什么你可以链接 .then.catch 方法

此外,这个问题:我是否应该始终使用 asych / await:

让我们了解一下 asyncawait 关键字的作用(您需要了解这一点,然后您会知道在哪里以及为什么需要使用它们)。

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 完成并将承诺转换为响应

// 只是虚拟示例

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');
        }
      });
  };