title: Node.js database insertion from a file with Sequelize
body: <p>Maybe I don't understand fully promises or Sequalize, but after some time working with it, get a feeling that async DB operations works well only for simpler cases.
  And by number of questions asking for synchronous DB access it looks I'm not the only.</p>
  <p>Here is my case. Suppose we have CSV file with compounds, where each line holds information about compound, and semicolon separated list of its ingredients. And we want to populate Ingredient table from it, but without duplications.</p>
  <p>For example, if file contains rows</p>
  <blockquote>
  <p>C1 IngA;IngB</p>
  <p>C2 IngA;IngC</p>
  </blockquote>
  <p>We want Ingredient table with three records, IngA, IngB, and IngC.
  So when line is read, it should save compound, for each ingredient check if already exists, and if not add it. Here is the code:</p>
  <pre><code>var lineReader=require('readline').createInterface({
    input: require('fs').createReadStream(filename)
  });
  
  lineReader.on('line', function(line) {
  
  let parts=line.split('\t');
  compoundModel.create({
    name: parts[0],
  }).then(entity =&gt; {
    let ingredients=parts[1].split(';');
  
    ingredients.forEach((ing, index) =&gt; {
      ingModel.findOne({
        where: {name: ing}
      }).then(ingEntity =&gt; {
        if (ingEntity) {
          return ingEntity;
        }
        return ingModel.create({
          name: ing
        })
      });
    }).then(ingEntity =&gt; {
      //something else
    });
  });
  });    
   
  </code></pre>
  <p>The problem is that IngA gets inserted in a table twice. My guess is that find or create Sequelize methods returns promises, and line reading from a file is faster that DB insertion. So IngA from first row is not yet inserted when new line is read and IngA tried to be found.</p>
  <p>I've tried several approaches, but everything seems too complicated for this kind of task. And more importantly, doesn't work.</p>