
[英]How can I make the await subscribe block complete before executing next line of code?
[英]Next block of code execute earlier before the fetch how can I fixed that
它应该给我不是空输出,但我得到空输出。 如果我在代码块内部进行控制,但它在外部它给我null值这是正常工作这是代码:
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);
});
因为只要你在forEach()循环中写一个promise,forEach本质上是异步的。 执行下一个命令,在您的情况下是:
// Here I get null output
await console.log(docData);
您需要此任务的典型for循环:
试试下面的代码:
let idListLen = idList.length;
for (let i =0; i< idListLen; i++) {
mahafuzCol.doc(id).get().then(
doc=>{
docData.push(doc.data());
//Here I get desire output w=if I log with console
}
);
}
console.log(docData) //prints the list of data
好的,看看你的代码,我想指出一些事情。
您正在使用最新最好的ES7异步和等待功能,非常棒。 为什么你坚持使用旧的定义变量的方式? 尝试使用let和const而不是var。 不要像这样混合ECMAScript版本。 这被认为是一种不好的做法。
Node.js中的循环现在是同步的(虽然异步循环在Node的管道中,我们很快就会看到它们)。 您不能将异步代码放在循环中并期望它们按预期工作。 Node.js中有一个event loop
概念,以及Node如何处理异步任务。 所以,如果你有时间,你一定要经历event loop
概念。
这是编写代码的更好方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.