如何等待异步.then

How to wait on async .then

这是我的代码:

let curId;
if (!user) {
  db.collection("users")
    .add({
      name: name,
    })
    .then((doc) => curId = doc.id)
    .catch((err) => console.error(err));
} else {
  curId = user.id;
}
console.log(curId); <-- I need curId here

目前 curId 未定义,因为我没有等待异步代码完成 运行。实现此目标的最佳方法是什么?

我想到的一些方法:

使用异步代码,您应该执行需要在 .then() 中等待结果的操作。有了这个,我看到了几个选项:

  1. 将其放入一个函数中,returns 承诺值
  2. 使用 curId 调用一个函数来执行您的逻辑
  3. 重组为单一承诺

选项 1

const getCurId = (user) => {
  if (!user) {
    return db.collection("users")
      .add({ name: name })
      .then((doc) => doc.id)
  } else {
    return Promise.resolve(user.id);
  }
};

getCurId().then(curId => {
  console.log(curId); // do things with curId here
}).catch((err) => console.error(err));

选项 2

if (!user) {
  db.collection("users")
    .add({ name: name })
    .then((doc) => doc.id)
    .then(doThingWithCurId)
    .catch((err) => console.error(err));
} else {
  doThingWithCurId(user.id);
}

const doThingWithCurId = (curId) => {
  console.log(curId); // do things with curId here
};

选项 3

const curIdPromise = user ? Promise.resolve(user.id) : db.collection("users")
  .add({ name: name })
  .then((doc) => doc.id);

curIdPromise.then((curId) => {
  console.log(curId); // do things with curId here
}).catch((err) => console.error(err));