当必须发出两个请求并且另一个请求需要第一个请求的响应时使用异步

发布于 2025-01-10 16:21:16 字数 922 浏览 0 评论 0原文

我有一个像这样的异步函数:

exports.myFunction = async (req, res, next) => {
  if (some condition) {
     next()
  }

  try {

    const results = await axios.get(`https://a-domain.com/url/path`);
    const info = results.data;

    const docRef = await addDoc(collection(db, "name_of_collec"), info);
    console.log("Document written with ID: ", docRef.id);
  } catch (e) {
    console.error("Error adding document: ", e);
  }

  next();
};

在这里,第二个请求需要第一个请求的响应。但据我所知,由于我正在发出异步请求,因此两个请求应该同时发出。

我不明白的是:

  • 那么,怎么可能不发生错误呢?
  • 有时没有文档添加到 Firestore 中,这是怎么回事?就像它以某种方式被跳过一样...
  • 可以进行哪些修改以便 await addDoc(collection(db, "name_of_collec") 强制执行?

上下文信息:

  • 我正在使用 Express.js 和 Node.js制作后端
  • 我使用 Axios 发出第一个请求,第二个请求是将文档添加到 Firestore 中,
  • Firestore 是 Google Firebase 中的一个 NoSQL 数据库。

I have a async function like this:

exports.myFunction = async (req, res, next) => {
  if (some condition) {
     next()
  }

  try {

    const results = await axios.get(`https://a-domain.com/url/path`);
    const info = results.data;

    const docRef = await addDoc(collection(db, "name_of_collec"), info);
    console.log("Document written with ID: ", docRef.id);
  } catch (e) {
    console.error("Error adding document: ", e);
  }

  next();
};

Here, response from the first request is required in the second request. But according to my knowledge since I am making asynchronous requests, the two requests should be made at the same time.

What I cannot understand:

  • So, how it is possible that there is no error occurring?
  • How is it that, sometimes the no document is added to Firestore? Like it is skipped somehow...
  • What modification can be done so that await addDoc(collection(db, "name_of_collec") executes compulsorily?

Context info:

  • I am using Express.js and Node.js to make a backend
  • I am using Axios to make the first request and the second one is adding a document to Firestore.
  • Firestore is a NoSQL database inside Google's Firebase.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情场扛把子 2025-01-17 16:21:16

但据我所知,由于我正在发出异步请求,
这两个请求应该同时提出。

异步并不意味着请求是同时发出的。这意味着代码不会等待这些请求的响应。请求以您在代码中添加请求的方式发出,响应将是异步的,即响应将在未来的某个时间点收到。

并且无法保证将以何种方式收到它们。

但是,当您起诉async/await时,代码执行将根据其成功或失败在await关键字处等待响应,并调用下一个流程。它只不过是承诺的语法糖。在幕后,您的代码将如何执行:

exports.myFunction = async (req, res, next) => {
  if (some condition) {
     next()l
  }

  axios.get(`https://a-domain.com/url/path`).then(result => result).then(data => {
      const info = data;
      
      addDoc(collection(db, "name_of_collec"), info).then(response => {
        console.log("Document written with ID: ", docRef.id);
      }).catch(e => {
        console.error(e);
      })
  }).catch(e => {
    console.error(e);
  })

   next();
};

那么,怎么可能不发生错误呢?

当您请求时,不一定会发生错误。如果是这种情况,应该激活 catch 处理程序。

有时候没有文档被添加到 Firestore 中,这是怎么回事?喜欢
它以某种方式被跳过...

原因可能是 info 是一个空对象,并且 firestore 会自动删除空文档。

没有问题,但有时没有数据 info 为空而跳过添加(它确实请求 firestore,但 firestore 删除了空文档)

exports.myFunction = async (req, res, next) => {
  if (some condition) {
     next()
  }

  try {

    const results = await axios.get(`https://a-domain.com/url/path`);
    const info = results.data;
    const is_Info_Data = Array.isArray(info) ? info?.length >= 1: Object.keys(info) !== 0 
    if (is_Info_Data) {
      const docRef = await addDoc(collection(db, "name_of_collec"), info);
    console.log("Document written with ID: ", docRef.id);
    } else {
      console.log(`Info is empty ${info} no addition to DB`);
    }
    
    next();
  } catch (e) {
    console.error("Error adding document: ", e);
    next(e);
  }

};

But according to my knowledge since I am making asynchronous requests,
the two requests should be made at the same time.

asynchronous doesn't mean that the requests are made at the same time. It means the code won't wait for the responses from these requests. Requests are made in the manner you add them in the code and responses will be asynchronous i.e the response will be received at some point in future time.

And there is no guarantee in what manner they will be received.

However, when you sue async/await, the code execution waits at await keyword for the response based on its success or failure it calls the next flow. It is nothing but syntactic sugar on promises. Under the hood, this is how your code will be executed:

exports.myFunction = async (req, res, next) => {
  if (some condition) {
     next()l
  }

  axios.get(`https://a-domain.com/url/path`).then(result => result).then(data => {
      const info = data;
      
      addDoc(collection(db, "name_of_collec"), info).then(response => {
        console.log("Document written with ID: ", docRef.id);
      }).catch(e => {
        console.error(e);
      })
  }).catch(e => {
    console.error(e);
  })

   next();
};

So, how it is possible that there is no error occurring?

It is not necessary that the error occurs when you request. If that is the case catch handler should be activated.

How is it that, sometimes the no document is added to Firestore? Like
it is skipped somehow...

The reason might be info is an empty object and firestore automatically removes the empty document.

There is no issue, but there is not data info that is empty sometimes that skips the addition(it does request firestore, but firestore removes the empty docs)

exports.myFunction = async (req, res, next) => {
  if (some condition) {
     next()
  }

  try {

    const results = await axios.get(`https://a-domain.com/url/path`);
    const info = results.data;
    const is_Info_Data = Array.isArray(info) ? info?.length >= 1: Object.keys(info) !== 0 
    if (is_Info_Data) {
      const docRef = await addDoc(collection(db, "name_of_collec"), info);
    console.log("Document written with ID: ", docRef.id);
    } else {
      console.log(`Info is empty ${info} no addition to DB`);
    }
    
    next();
  } catch (e) {
    console.error("Error adding document: ", e);
    next(e);
  }

};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文