【发布时间】:2014-06-19 11:59:35
【问题描述】:
我在 nodejs 上的一个异步进程遇到了一些问题。
我从远程 JSON 获取一些数据并将其添加到我的数组中,这个 JSON 有一些重复的值,我需要在添加之前检查它是否已经存在于我的数组中以避免数据重复。
我的问题是,当我开始 JSON 值之间的循环时,循环调用下一个值之前的最新处理完成,因此,我的数组填充了重复的数据,而不是每个类型只维护一个项目。
看看我当前的代码:
BookRegistration.prototype.process_new_books_list = function(data, callback) {
var i = 0,
self = this;
_.each(data, function(book) {
i++;
console.log('\n\n ------------------------------------------------------------ \n\n');
console.log('BOOK: ' + book.volumeInfo.title);
self.process_author(book, function() { console.log('in author'); });
console.log('\n\n ------------------------------------------------------------');
if(i == data.length) callback();
})
}
BookRegistration.prototype.process_author = function(book, callback) {
if(book.volumeInfo.authors) {
var author = { name: book.volumeInfo.authors[0].toLowerCase() };
if(!this.in_array(this.authors, author)) {
this.authors.push(author);
callback();
}
}
}
BookRegistration.prototype.in_array = function(list, obj) {
for(i in list) { if(list[i] === obj) return true; }
return false;
}
结果是:
[{name: author1 }, {name: author2}, {name: author1}]
我需要:
[{name: author1 }, {name: author2}]
更新:
@Zub 建议的解决方案适用于数组,但不适用于 sequelize 和 mysql 数据库。
当我尝试将作者列表保存到数据库时,数据重复,因为系统在完成保存最后一个之前开始保存另一个数组元素。
这个案例的正确模式是什么?
我使用数据库的代码是:
BookRegistration.prototype.process_author = function(book, callback) {
if(book.volumeInfo.authors) {
var author = { name: book.volumeInfo.authors[0].toLowerCase() };
var self = this;
models.Author.count({ where: { name: book.volumeInfo.authors[0].toLowerCase() }}).success(function(count) {
if(count < 1) {
models.Author.create(author).success(function(author) {
console.log('SALVANDO AUTHOR');
self.process_publisher({ book:book, author:author }, callback);
});
} else {
models.Author.find({where: { name: book.volumeInfo.authors[0].toLowerCase() }}).success(function(author) {
console.log('FIND AUTHOR');
self.process_publisher({ book:book, author:author }, callback);
});
}
});
// if(!this.in_array(this.authors, 'name', author)) {
// this.authors.push(author);
// console.log('AQUI NO AUTHOR');
// this.process_publisher(book, callback);
// }
}
}
如何避免异步进程中的数据重复?
【问题讨论】:
标签: arrays json node.js asynchronous