很不幸,我对Node还很陌生,关于Node的异步/同步执行会有些困惑。
我正在使用Node、sequelize和sqlite以及async.js。
我有一系列的“文章”,每篇文章都有若干个“作者”。
对于每个“文章”的每个“作者”,我想检查是否存在该作者。如果不存在,则创建它。
问题是,在初始运行时,由于异步功能导致检查存在性出现了问题,会出现重复创建作者的情况。
例如,对于数组:authors = ['A. Test', 'B. Test', 'C. Test', 'A. Test']
以及以下代码:
async.each(authors, function(item, callback){
Author.sync().then(function(){
Author.count({ where: {name: item.trim()} }).then(function(count){
if (count != 0) {
console.log('Author already exists')
} else {
console.log('Creating author...')
Author.create({
name: item.trim()
})
}
})
})
})
在第一次运行时,将创建一个表:
ID | name
------------
0 | A. Test
1 | B. Test
2 | C. Test
3 | A. Test
我做错了什么?我似乎缺少了在Node中异步与同步执行的基本概念。
(我也尝试过async.eachSeries,它应该是按顺序而非并行执行的?)
编辑:稍微重构了一下,但仍然会创建重复项
async.eachSeries(authors, function(authorName, callback){
Author.findOne({ where: {name: authorName.trim()} }).
then(function(author){
if (author) {
// Author exists...
callback()
} else {
// Author does not exist...
Author.create({
name: authorName.trim()
}).then(function(author){
callback()
})
}
})
})
findOrCreate
(并重构了一些更干净的代码片段添加到我的答案中),但是findOrCreate
在 sqlite 中引起了各种问题,比如数据库锁定等 - 显然这也会发生在某些 postgres 用户身上。不幸的是,我的新代码片段仍然无法正常工作,并且仍然会创建重复项。 - waffl.spread(function(author, isCreated) { ... });
- Ali BARIN