gpt4 book ai didi

node.js - 当有足够的 RAM 可用时,大量的回调会破坏脚本还是继续执行?

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:33 25 4
gpt4 key购买 nike

我有一个函数,可以从数据库中获取线程(gmail 对话)ID,然后向 Google API 请求每个线程 ID 的所有数据。一旦它接收到一个线程对象,它就会将其存储到数据库中。这对于我有大约 1k 条消息的收件箱来说效果很好。但我不确定它是否适用于拥有超过 10 万条消息的帐户。

现在我要问的是,一旦机器内存不足,它会崩溃还是会在再次有足够的 RAM 可用时继续执行回调函数?我是否应该修改此代码来逐部分执行此操作(在某些时候重新运行整个脚本并从上次结束的位置继续使用新的 RAM?)

function eachThread(auth) {
var gmail = google.gmail('v1');

MongoClient.connect(mongoUrl, function(err, db){
assert.equal(null, err);
var collection = db.collection('threads');
// Find all data in collection and convert it to array
collection.find().toArray(function(err, docs){
assert.equal(null, err);
var threadContents = [];
// For each doc in array...
for (var i = 0; i < docs.length; i++) {
gmail
.users
.threads
.get( {auth:auth,'userId':'me', 'id':docs[i].id}, function(err, resp){
assert.equal(null, err);
threadContents.push(resp);
console.log(threadContents.length);
console.log(threadContents[threadContents.length - 1].id);
var anotherCollection = db.collection('threadContents');
anotherCollection.updateOne(
{id: threadContents[threadContents.length - 1].id},
threadContents[threadContents.length - 1],
{upsert:true},
function(err, result){
assert.equal(null, err);
console.log('updated one.');
});
if (threadContents.length === docs.length) {
console.log('Length matches!');
db.close();
}
});//end(callback(threads.get))
}//end(for(docs.length))
});//end(find.toArray)
});//end(callback(mongo.connect))
}//end(func(eachThread))

最佳答案

如果您不获取所有内容并将其推送到数组,则不会耗尽内存。另外,我不会实例化循环内每个元素上都相同的对象。

这里是不会耗尽内存的代码示例,但是它是“即发即忘”的,意味着您在完成后不会收到回调等。如果您希望这样做,您将需要使用 Promise/async。

// Fire-and-forget type of function
// Will not run out of memory, GC will take care of that
function eachThread(auth, cb) {
var gmail = google.gmail('v1');

MongoClient.connect(mongoUrl, (err, db) => {
if (err) {
return cb(err);
}

var threadsCollection = db.collection('threads').find();
var contentsCollection = db.collection('threadContents');

threadsCollection.on('data', (doc) => {
gmail.users.threads.get({ auth: auth, 'userId': 'me', 'id': doc.id }, (err, res) => {
if (err) {
return cb(err);
}

contentsCollection.updateOne({ id: doc.id }, res, { upsert: true }, (err, result) => {
if (err) {
return cb(err);
}
});
});
});

threadsCollection.on('end', () => { db.close() });
});
}

关于node.js - 当有足够的 RAM 可用时,大量的回调会破坏脚本还是继续执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39267355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com