Node + Sequelize:如何在添加之前检查项目是否存在? (asynchronous混淆)

不幸的是,对于节点的asynchronous/同步执行,我对节点很陌生。

我正在使用节点,与sqlite和async.js sequelize。

我有一系列的Articles ,每个Articles都有一些Authors

对于每篇Article每位Authors ,我想检查Author存在。 如果没有,创build它。

问题是,在最初运行时,重复作者正在创build,我认为由于asynchronousfunction导致检查存在的问题。

例如,用数组: authors = ['A. Test', 'B. Test', 'C. Test', 'A. Test'] 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() }) } }) }) }) 

在第一次运行时,将创build一个表格:

 ID | name ------------ 0 | A. Test 1 | B. Test 2 | C. Test 3 | A. Test 

我究竟做错了什么? 我似乎错过了Node中asynchronous与同步执行的基本概念。

(我也试过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() }) } }) }) 

Author.count不是真的需要,除非你需要计数。 请参阅findOrCreate() 。

findOrCreate()你可以有以下。 (编辑trex005的片段)

 async.eachSeries(authors, function(item, callback) { Author.sync().then(function() { Author.findOrCreate({ where: { name: item.trim() }, defaults: { // set the default properties if it doesn't exist name: item.trim() } }).then(function(result) { var author = result[0], // the instance of the author created = result[1]; // boolean stating if it was created or not if (created) { console.log('Author already exists'); } console.log('Created author...'); callback(); }); }) }) 

改变你的每个到每个eachSeries ,实际上调用callback,你应该是金。

 async.eachSeries(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') callback(); //assuming you want it to keep looping, if not use callback(new Error("Author already exists")) } else { console.log('Creating author...') Author.create({ name: item.trim() }).then(function(author){ callback(); }) } }) }) })