它应该给我非空输出,但我得到空输出。如果我在代码块内部进行控制台,但在代码块外部给我空值,则它工作正常 这是代码:
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);
});
最佳答案
好吧,看看你的代码,我想指出一些事情。
您正在使用最新、最好的 ES7 异步和等待功能,这非常棒。为什么你仍然坚持定义变量的旧方法?尝试使用 let 和 const 而不是 var。不要像这样混合 ECMAScript 版本。这被认为是一种不好的做法。
到目前为止,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/