gpt4 book ai didi

javascript - promise -mongo : can't finalize promise

转载 作者:行者123 更新时间:2023-11-28 19:25:17 26 4
gpt4 key购买 nike

这是我正在处理的一段代码:它将 reddit 帖子保存到 mongoDB 集合中。

我正在使用promised-mongo图书馆

问题是,当 for 循环完成并且所有数据都保存到数据库时,程序不会退出,它会继续执行而不执行任何操作,尽管在每个 promise 结束时调用了 done() -蒙戈 promise 链。

    for (var i = 0; i< posts.length; i++) { 
posts[i].done = false;
DB.posts.findOne({
"id" : posts[i].id // it's 'id', not mongo's '_id'
})
.then(function(i) {
return function(doc){
if(doc) {
console.log('skipping')
} else {
DB.posts.insert(posts[i]).then(function() {
console.log(arguments);
nSaved++;
});
}
}
}(i))
.catch(function(){
console.log(arguments)
})
.done();
}

我做错了什么?

最佳答案

这里有一些问题:

  • 您正在 for 中创建多个 Promise循环,但不跟踪它们
  • 您有 DB.posts.insert这创造了一个 promise ,但你并没有等待它

以相反的顺序处理它们:

如果你不返回DB.posts.insert创建的promise没有办法等待它完成。您需要归还它:

return function(doc){
if(doc) {
console.log('skipping')
} else {
// here
return DB.posts.insert(posts[i]).then(function() {
console.log(arguments);
nSaved++;
});
}
}

您还需要跟踪您正在创建的所有 promise ,以便您知道它们何时全部完成。执行此操作的一个简单方法是使用 .map()将它们映射到 Promise 数组,然后使用 Promise.all()等待他们。

假设posts是一个数组:

function ensurePost(post) {
post.done = false;

return DB.posts.findOne({
"id" : post.id // it's 'id', not mongo's '_id'
})
.then(function(doc){
if(doc) {
console.log('skipping ' + post.id)
} else {
return DB.posts.insert(post).then(function() {
console.log(arguments);
nSaved++;
});
}
})
.catch(function(error){
console.error('Error inserting', post.id, error);
});
}

Promise.all(posts.map(ensurePost))
.done(function () {
// all done. close the connection
});

这也消除了您在那里所经历的令人不快的 IIFE 的需要。

关于javascript - promise -mongo : can't finalize promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28000060/

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