Put number first function respond with this: Promise { <pending> }

Issue

I am using the following function to put some data into dynamo DB table but I am getting this response that Put number first function responds with this: Promise { pending }
Here is the code

 async function putNumberFirst(phoneNumber) {
         return new Promise(function(resolve, reject) {
          console.log("inside put Numer function");
             let params = {
                 TableName: process.env.CHAT_DATA_TABLE,
                 Item: {
                     'phoneNumber': phoneNumber
                 }

             };
             console.log("PARAMS", params);
             docClient.put(params, function(err, results) {
                 if (err) {
                     console.error(
                         "Unable to put new connection data. Error:",
                         JSON.stringify(err, null, 2)
                     );
                     reject();
                 }
                 else {
                     console.log("Put succeeded.", results);
                     resolve("Success!");
                 }
             });
         });

     }

any help would be appreciated

Solution

You’re mixing up async functions, promises and callbacks. I suggest you try to understand these very important topics first: https://towardsdev.com/callback-vs-promises-vs-async-await-29572e4a0c8

Here’s my editorialized async/await take on your code sample:

const putNumberFirst = async (phoneNumber) => {
  const params = {
      TableName: process.env.CHAT_DATA_TABLE,
      Item: { phoneNumber }
  };

  try {
      console.log("Params: ", params);
      const results = await docClient.put(params).promise();
      console.log('Put succeeded: ', results);
      return results;
  } catch (err) {
      console.error('Unable to put new connection data. Error:', JSON.stringify(err, null, 2));
      throw err;
  }
}

Then, from wherever you want to call the putNumberFirst function, you need to await the response:

await putNumberFirst(number);

Please keep in mind that await is available only in async functions, you may have to restructure your code accordingly.

You could use then/catch or a callback instead of async/await, but please, do not mix these things up unless absolutely necessary. Async code is the bread and butter of JS, it’s absolutely critical that you understand how it works. Invest some time into it, it will be worth it.

Answered By – Scaccoman

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.