Postgres promise multiple queries - nodejs
<p>After reading <a href="https://stackoverflow.com/a/14797359/4158593">https://stackoverflow.com/a/14797359/4158593</a> : about nodejs single thread and that it takes the first parameter of async function, processes it and then uses the callback to respond when everything is ready. What confused me is what if I had multiple queries that need to be excused all at once and tell nodeJS to block other requests by adding them in a queue. </p>

<p>To do that I realised that I need to wrap my queries in another <code>callback</code>. And promises do that pretty well. </p>

<pre><code>    const psqlClient = psqlPool.connect(); 
    return psqlClient.query(`SELECT username FROM usernames WHERE username=$1`, ['me'])
    .then((data) =&gt; {
        if(!data.rows[0].username) {
           psqlClient.query(`INSERT INTO usernames (username) VALUES ('me')`);
        }
       else { ... } 
 });
</code></pre>

<p>This code is used during sign up, to check if username isn't taken before inserting. So it very important that nodejs puts other requests into a queue, and makes sure to <code>select</code> and <code>insert</code> at the same time. Because this code might allow people with the same username sent at the same time to select a username that has been already been taken, therefore two usernames will be inserted.</p>

<p><strong>Questions</strong></p>

<ol>
<li><p>Does the code above executes queries all at once? </p></li>
<li><p>If <code>1</code> is correct, if I was to change the code like this </p>

<pre><code>const psqlClient = psqlPool.connect(); 
return psqlClient.query(`SELECT username FROM usernames WHERE username=$1`, ['me'], function(err, reply) { 
if(!reply.rows[0].username) {
psqlClient.query(`INSERT INTO usernames (username) VALUES ('me')`);
}
});
</code></pre>

<p>would that effect the behaviour? </p></li>
<li><p>If <code>1</code> is wrong, how should this be solved? I am going to need this pattern (mainly using <code>select</code> and <code>insert/update</code> one after another) for things like making sure that my XML sitemaps don't contain more than 50000 urls by storing the count for each file in my db which happens dynamically. </p></li>
</ol>