title: Node JS Async Execution
body: <p>I’m newish to Node Js and Async processing. I’m working on a discord bot that is integrated with AWS. My problem is everything I have tried, async/await or wrapping in Promise’s has not fixed the issue of the rest of the code executing before the async process finishes. AWS calls are mostly async in general, but I’m trying to create a sync process (checking is an item already exists before adding it). Right now, the check is not finishing in time, so the item gets re-added.</p>
  <p><strong>EDIT</strong>
  BELOW IS MY EDITED CODE AND OUTPUT</p>
  <pre><code>const AWSUtil = require(&quot;../utils/aws/awsUtil&quot;)
  
  module.exports = async (client, message) =&gt; {
    
    const aws = new AWSUtil()
    const tableName = &quot;Discord-Server&quot;
    
    let serverName = message.guild.name.replace(/[^a-zA-Z ]/g, &quot;&quot;).replace(' ', '-')
    let serverID = message.guild.id
    
    if (message.member.hasPermission(&quot;ADMINISTRATOR&quot;)){
      var doesExist = await doesServerExist()
      console.log(`doesExist ----- ${doesExist}`)
      if(!doesExist){
        console.log(&quot;5 server is not already enrolled, adding the server...&quot;)
        aws.addDynamoDBItem(addServerParams())
        console.log(&quot;6 server successfully added&quot;)
        message.reply(`${message.guild.name} has been successfully enrolled to SMSAlert!`)
      } else {
        console.log(&quot;5 server already enrolled...&quot;)
        message.reply(`${message.guild.name} is already enrolled to SMSAlert.`)
      }
     
      } else {
        return message.reply(&quot;You do not bave permissions to enroll the server.&quot;)
      }
  
  async function doesServerExist(){
    console.log(&quot;1 Calling AWS util&quot;)
    var response = await aws.getDynamoDBItem(checkExistParams())
    //The below line never prints
    console.log(&quot;4 Returning if server exists&quot;)
    console.log(Object.keys(response))
    return !Object.keys(response).length == 0
  }
  
  function addServerParams(){
  return params = {
      TableName:tableName,
      Item:{
          &quot;server-id&quot;: serverID,
          &quot;server-name&quot;: serverName,
          &quot;topics&quot;:[]
      }
  };
  }
  
  function checkExistParams(){
    return params = {
      TableName: tableName,
      Key:{
          &quot;server-id&quot;: { S: serverID }
      }
  };
  }
  
  }
  </code></pre>
  <p>THE BELOW IS MY AWSUTIL CLASS</p>
  <pre><code>var AWS = require('aws-sdk');
  
  class AWSUtil {
    
    constructor(){
      AWS.config.loadFromPath('./config/aws/config.json');
    }
    
    async getDynamoDBItem(params){
      console.log(&quot;2 Get Dynamo Item...&quot;)
      const docClient = new AWS.DynamoDB.DocumentClient();
      
      const awsRequest = await docClient.scan(params);
      const result = await awsRequest.promise();
      console.log(result.Items);
      console.log(&quot;3 Returning getItem data&quot;)
      return results.Items
    }
    
    async addDynamoDBItem(params){
      console.log(&quot;Adding a new item...&quot;);
      var docClient = new AWS.DynamoDB.DocumentClient();
      const awsRequest = await docClient.put(params);
      const result = await awsRequest.promise();
      console.log(&quot;Added item:&quot;, JSON.stringify(result))
      //docClient.put(params, function(err, data) {
      //if (err) {
          //console.error(&quot;Unable to add item. Error JSON:&quot;, JSON.stringify(err, null, 2));
      //} else {
          //console.log(&quot;Added item:&quot;, JSON.stringify(data, null, 2));
      //}
  //});
    }
    
    removeDynamoDBItem(params){
      console.log(&quot;Attempting to delete...&quot;);
      var docClient = new AWS.DynamoDB.DocumentClient();
  docClient.delete(params, function(err, data) {
      if (err) {
          console.error(&quot;Unable to delete item. Error JSON:&quot;, JSON.stringify(err, null, 2));
      } else {
          console.log(&quot;DeleteItem succeeded:&quot;, JSON.stringify(data, null, 2));
      }
  });
    }
  }
  
  module.exports = AWSUtil
  </code></pre>
  <p>THE BELOW IS MY OUTPUT</p>
  <pre><code>1 Calling AWS Util 
  2 Get Dynamo Item...
  [
  My item
  ]
  3 Returning getItem data
  </code></pre>
  <p>I have the below in my main file.</p>
  <pre class="lang-js prettyprint-override"><code>if (message.member.hasPermission(&quot;ADMINISTRATOR&quot;)) {
    if (!doesServerExist()) {
      console.log(&quot;server is not already enrolled, adding the server...&quot;);
      aws.addDynamoDBItem(addServerParams());
      console.log(&quot;server successfully added&quot;);
      //return message.reply(`You have successfully enrolled ${message.guild.name} to SMSAlerts.`)
    } else {
      console.log(&quot;server already enrolled...&quot;);
      //return message.reply(`${message.guild.name} is already enrolled to SMSAlert`)
    }
  } else {
    return message.reply(&quot;You do not bave permissions to enroll the server.&quot;);
  }
  
  function isEmptyObject(obj) {
    return !Object.keys(obj).length;
  }
  
  function doesServerExist() {
    return isEmptyObject(aws.getDynamoDBItem(checkExistParams()));
  }
  </code></pre>
  <p>And below is my AWS call</p>
  <pre class="lang-js prettyprint-override"><code>async getDynamoDBItem(params) {
      console.log(&quot;Get Dynamo Item...&quot;)
      var dynamodb = new AWS.DynamoDB({
          apiVersion: '2012-08-10'
      });
      var response = null
      await dynamodb.getItem(params, function(err, data) {
          if (err) {
              console.error(&quot;Unable to read item. Error JSON:&quot;, JSON.stringify(err, null, 2));
          } else {
              response = data
          }
      }).promise()
      return response
  }
  </code></pre>