title: How to reattempt inserting into database if there was already such unique value stored
body: <p>I searched for any existing patterns but didn't happen to find anything.</p>
  
  <p>So, the thing is I want to store in my MySQL database some <code>key</code> value which would be <em>unique</em>. I generate it on server side like that:</p>
  
  <pre><code>var pc = require('password-creator');
  var key = pc.create(20); //  "f9Wp&gt;=\qJqx]rwwbbiQ8
  </code></pre>
  
  <p>Then I send it to database:</p>
  
  <pre><code> connection.query(db_query, function (err, rows, fields) {
      if(err){
          if(err.code == "ER_DUP_ENTRY"){
              // here I could attempt again with newly generated key by
              // calling another query to database but this is giving me 
              // a limited amount of such attempts
          }
      }
      else{
          // there was no duplicate
      }
  });
  </code></pre>
  
  <p>So everything seems fine but there is a slight possibility to get <code>ER_DUP_ENTRY</code>. And now is my question:</p>
  
  <p>How to solve such situation <strong>the right way</strong>? I mean that I always want to input some <code>key</code> value in database. I thought of loops but this feels stupid because it's an asynchronous query to database. I'm basically looking for the right approach in such situations.</p>