javascript - 下一个代码块在获取之前更早执行我该如何解决这个问题

标签 javascript node.js firebase

它应该给我非空输出,但我得到空输出。如果我在代码块内部进行控制台,但在代码块外部给我空值,则它工作正常 这是代码:

app.post("/downloadDb",async (req,res)=>{
 var docData = [];
 var idList = [];
  console.log("downloadBd");
  const mahafuzCol = firestore.collection("Mahafuz")
  await mahafuzCol.listDocuments()
  .then( listDoc=>{
   //List of id fetch 

    listDoc.forEach(data=>{
      idList.push(data.id)
    });
  }).catch(e=>console.log(e));


  //document is fetched 
  await idList.forEach(id=>{
    mahafuzCol.doc(id).get().then(
      doc=>{
        docData.push(doc.data());
        //Here I get desire output w=if I log with console
      }
    );
  });

//Here I get null output
  await console.log(docData);
});

最佳答案

好吧,看看你的代码,我想指出一些事情。

  1. 您正在使用最新、最好的 ES7 异步和等待功能,这非常棒。为什么你仍然坚持定义变量的旧方法?尝试使用 let 和 const 而不是 var。不要像这样混合 ECMAScript 版本。这被认为是一种不好的做法。

  2. 到目前为止,Node.js 中的循环是同步的(尽管异步循环正在 Node 的管道中,我们很快就会看到它们)。您不能将异步代码放入循环中并期望它们按预期工作。 Node.js 中有一个完整的事件循环概念以及 Node 如何处理异步任务。因此,如果您有时间,您一定应该了解一下事件循环概念。

这是编写代码的更好方法:

app.post('/downloadDb', async (req, res) => {
  // always wrap asynchronous code in async/await in try/catch blocks
  console.log('downloadBd');

  const mahafuzCol = firestore.collection('Mahafuz');

  try {
    // assuming that listDocuments returns a promise
    // await on it until it gets resolved
    // all the listed documents will be assigned to docs
    // once the promise is resolved
    const docs = await mahafuzCol.listDocuments();

    const idList = docs.map(data => data.id);

    // again assuming that get() returns a promise
    // pushing all the promises to an array so that
    // we can use Promise.all to resolve all the promises
    // at once
    const promisesList = idList.map(id => mahafuzCol.doc(id).get());

    // fetching document is here
    // once all the promises are resolved, data contains
    // the result of all the promises as an array
    const data = await Promise.all(promisesList);

    const docData = data.map(doc => doc.data());

    console.log(docData);

    // return some response
    return res.status(200).send();
  } catch (error) {
    console.log('error: ', error);

    // return some response
    return res.status(500).send();
  }
});
PS: 如果您仍然想使用异步循环,请看看这个库 https://caolan.github.io/async/docs.html#each

关于javascript - 下一个代码块在获取之前更早执行我该如何解决这个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55644102/

相关文章:

javascript - Firebase Passwordless Auth 在点击链接时显示网站未找到页面

javascript - 在 Tampermonkey 中获取跨度文本的值

java - 如何在 Firebase 中收听多个 child ?

android - 如何在flutter中将列表对象发布到cloud firestore firebase

javascript - 处理/捕获错误而不重复代码?

node.js - 使用 Bookshelf.js 在数据透视模型上设置时间戳

node.js - 使用 Aerospike Nodejs 客户端进行分页

javascript - 是否可以模拟 isTrusted=true

javascript - CSS Background-Images Loading after HTML Images(涉及Javascript)

javascript - 使用node.js检查mysql表