javascript - MongoDB Aggregation+Cursor 加上 JS Generators
问题描述
这是我第一次在 JavaScript (Node.js) 中使用生成器。我只是希望有人验证实现是否正确。如果没有,请提出更好的方法。
所以,这里有两个问题:
- 是否优化了基于生成器的实现。并且在优化之前,是否正确。(但是,我得到了结果,只是想从阻塞/非阻塞的角度来理解它)。
- 我正在使用 node-fetch 进行 10 次 API 调用并在数组中收集 Promise。如果我需要在 AWS Lambda 上部署它,如果我不使用 Promise.all(array) 并且无论 API 调用是否成功都简单地返回,是否可以?反正我不在乎反应。我只是触发 API。
要求:
- 在 AWS Lambda 上托管一个使用 Mongoose 驱动程序与 MongoDB 对话的 Node.js 函数。
- 从 MongoDB 中获取 10000 个文档。
- 这些文档具有以下架构。_id 键保存一个长度为 163 的字符串值:
{
_id: "cSKhwtczH4QV7zM-43wKH:APA91bF678GW3-EEe8YGt3l1kbSpGJ286IIY2VjImfCL036rPugMkudEUPbtcQsC"
}
- 我对 _ids 的值感兴趣,我一次只能处理 1000 个 _ids。
- 将它们放入一个数组并进行 API 调用。因此,对于 10000 个 _id,我需要使用其中的 10 个数组进行 10 次 API 调用。
我使用 Node.js 生成器进行的实现:
async function* generatorFunction() {
await connectMongo();
const cursor = Model.aggregate([
//... some pipeline here
]).cursor();
const GROUP_LIMIT = 1000;
let newGroup = [];
for await (const doc of cursor) {
if (newGroup.length == GROUP_LIMIT) {
yield newGroup;
newGroup = [];
}
newGroup.push(doc._id);
}
yield newGroup;
await disconnectMongo();
}
const gen = generatorFunction();
(async () => {
const promises = [];
for await (const newGroup of gen) {
// POST request using node-fetch
// Ignore the syntax
promises.push(fetch('API', { body: { newGroup } }));
}
// Do I need to do this?
// Or can this be skipped?
// I do not care about the response anyway...
// I just need to trigger the API and forget...
await Promise.all(promises);
return {
success: true,
};
})();
解决方案
推荐阅读
- java - Java 过滤器适用于一个谓词,但不适用于另一个谓词
- java - 如何从 swt.SelectionListener 中找到事件类型?
- laravel - Laravel Eloquent:在主要语句上应用“with where”过滤器
- jquery - 根据表单输入数创建多维数组
- jquery - JQuery 3.4.1 支持哪个版本的 bootstrap
- docker - 具有特定用户的 Gitlab CI 作业
- javascript - 哈希链接与导航菜单不匹配
- swift - 在 Swift 5 中的 applicationWillResignActive 中显示图像
- flutter - 如何防止关闭 CupertinoActionSheet/showCupertinoModalPopup?
- c# - Sage 200:无法将许多 *.dll 文件添加到我的 Visual Studio C# 项目中以使 Sage 200 基本功能正常工作