【发布时间】:2020-09-11 16:09:29
【问题描述】:
今天一直在到处寻找,我的脑袋已经到了我真的不知道该怎么办了。
我正在尝试做一些对我来说听起来很简单的事情。然而,异步工作流让我崩溃了。
- 从 Firestore 中的 crawlJobs 中查找每个 ID
- 在另一个集合中获取这些 ID 的所有文档
- 将输出添加到数组中
- 返回数组的输出
因为一切都是异步的,所以我被困在数字 2 和 3 上,因为数字 4 的执行速度比异步代码的执行速度要快。
我的大问题,我该如何处理?
这是我的全部功能:
exports.publicOutput = functions
.region("us-central1")
.runWith(runtimeOpts)
.https.onRequest(async (req, res) => {
const projectAlias = req.query.projectalias;
const apiKey = req.query.apikey;
let status = 404;
let data = {
Message:
"Unauthorized access! Please provide the correct authentication data.",
};
let response = data;
let scrapeStorage = [];
// check if credentials are provided
if (!projectAlias || !apiKey) {
return res.status(status).send(response);
}
// when both items provided execute this
if (projectAlias && apiKey) {
const snapshot = await db
.collection("AdaProjects")
.where("projectAlias", "==", projectAlias)
.where("hasAccess", "array-contains", apiKey)
.limit(1)
.get();
if (snapshot.empty) {
return res.status(status).send(response);
}
if (!snapshot.empty) {
snapshot.forEach((doc) => {
projectData = doc.data();
});
status = 200;
}
const crawlJobIDs = projectData.crawlJobs;
let scrapeIDs = [];
crawlJobIDs.forEach(async (jobID) => {
const snapshot = await db
.collection("scrapes")
.where("crawlJobID", "==", jobID)
.get();
if (snapshot.empty) {
console.log("not found jobID", jobID);
return;
}
snapshot.forEach((doc) => {
scrapeIDs.push(doc.id);
console.log(scrapeIDs); // here everything is fine. But this outputs (logically) after "DONE"
});
});
response = scrapeIDs;
}
console.log("DONE");
return res.status(status).send(response);
});
我还尝试将所有内容都放在一个函数中,并在函数的端点之前等待它。
async function getAllScrapeIDs(crawlJobIDs) {
let someData = [];
try {
crawlJobIDs.forEach(async (jobID) => {
const snapshot = await db
.collection("scrapes")
.where("crawlJobID", "==", jobID)
.get();
if (snapshot.empty) {
console.log("not found jobID", jobID);
return;
}
snapshot.forEach((doc) => {
someData.push(doc.id);
});
});
} catch (error) {
console.log(error);
return null;
}
return someData;
}
// and then later in the code
const crawlJobIDs = projectData.crawlJobs;
response = await getAllScrapeIDs(crawlJobIDs);
响应仍然为空,因为异步代码仍未更新。
我还尝试在没有 async/await 的情况下编写所有内容,并应用了 .then.catch 选项。相同的输出。我的函数在用我要输出的数据填充数组之前完成。
我觉得这部分 const crawlJobIDs = projectData.crawlJobs; 确实有效。也许是因为它只搜索一项?
【问题讨论】:
标签: javascript node.js firebase google-cloud-firestore google-cloud-functions