javascript - 为什么 async/await 会产生不同的结果

标签 javascript asynchronous google-cloud-firestore async-await promise

我问这个问题只是为了澄清并更好地理解 javascript promise 。下面的两个代码对我来说看起来非常相似,但是为什么两者给出了不同的结果。还有如何以.then方式获取async/await函数的结果。谢谢。

异步/等待

const getFieldValue = async (collection, userid) => {
  let response;

  const querySnapshot = await firestore()
    .collection(collection)
    .where("userid", "==", userid)
    .get();
  querySnapshot.forEach((doc) => {
    const { name } = doc.data();
    response = name;
  });

  return response;
};
async function fetchData() {
  const name = await getFieldValue("Users", userid);
  console.log("name", name);
}
fetchData();

.然后

const getFieldValue = (collection, userid) => {
  let response;

  firestore()
    .collection(collection)
    .where("userid", "==", userid)
    .get()
    .then((querySnapshot) => {
      querySnapshot.docs.find((doc) => {
        const { name } = doc.data();
        response = name;
      });
    })
    .catch((e) => console.log(e));

  return response;
};
const name = getFieldValue("Users", userid);
console.log("name", name);

async/await 返回正确的名称,.then 返回未定义

最佳答案

是的,这正是人们所期望的。

请记住,await 有效地暂停执行,直到等待的操作完成。

在使用 .then 的示例中,您会立即返回,因为您没有编写 promise 链,以便仅在等待的操作序列完成时才返回 response 。相反,您会立即返回初始化 responseundefined

因此,通过 .then 表达逻辑的正确方法(否则不改变)将是

 const getFieldValue = (collection, userid) => {
    let response;

    return firestore() // notice the return here! This is vital
      .collection(collection)
      .where("userid", "==", userid)
      .get()
      .then((querySnapshot) => {           
        querySnapshot.docs.find((doc) => {
          const { name } = doc.data();
          response = name;
        });
      })
      .then(() => response) // notice how we resolve our promise chain with the value ultimately assigned
      .catch((e) => console.log(e));
};

关于javascript - 为什么 async/await 会产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70503710/

相关文章:

javascript - 如何将值从一个 Jasmine JavaScript 测试传递到另一个测试

firebase - map 中未知键的 Firestore 安全规则

flutter - 火存储 : multiple where()'s and orderBy()

javascript - 忽略图像的透明 Angular

javascript - 动态更改 svg 的颜色并在 Three.js 中应用为纹理

javascript - 倒计时不起作用

python - 为什么只有一个工作线程的 ThreadPoolExecutor 仍然比正常执行速度更快?

.net - apache apollo mq 与 .NET

javascript - 如何克服异步useState钩子(Hook)?

firebase - 在Cloud Firestore中提取所有用户数据