Javascript code not running in order while getting data from database

Tags: ,



I have two functions as shown below. It is essentially just getting data from a database.

function processRequest(query){
    let dynamoData = getDynamoData(query);
    console.log('abc')
}


function getDynamoData(key){
    var params = {
        TableName: 'test_table',
        Key: {
          'TWEET_KEY' : {S: String(key)}
        }
      };
      
      // Call DynamoDB to read the item from the table
      ddb.getItem(params, function(err, data) {
        if (err) {
            console.log("Error");
        } else {
            console.log("Successfully got data from table")
            return data.Item;
        }
      });
}

Currently when I run the code, within the console it prints the following:

abc
Successfully got data from table

However, I need it to print Successfully got data from table before it prints abc.

I know I have to possibly use async within the function however am really struggling to get the code running in order. Would really appreciate it if anyone could help me get the code running in order. Thank you!

Answer

You should move both functions into a separate module (if this wasn’t done yet) and make them async ones like this:

async function processRequest(query){
    let dynamoData = await getDynamoData(query);
    console.log('abc')
}

async function getDynamoData(key){
    var params = {
        TableName: 'test_table',
        Key: {
          'TWEET_KEY' : {S: String(key)}
        }
      };
      
  return new Promise((resolve, reject) => {
      // Call DynamoDB to read the item from the table
      ddb.getItem(params, function(err, data) {
        if (err) {
            console.log("Error");
            reject(err);
        } else {
            console.log("Successfully got data from table")
            resolve(data.Item);
        }
      });
  });
}



Source: stackoverflow