0

I'm writing an async function to query a DynamoDB table using the AWS SDK:

async function fetchData() {
  try {
    var params = { Key: { chart_name: "cambridge_rent" }, TableName: "charts" };
    const data = await docClient.get(params).promise();
    return data.Item.values;
  } catch (err) {
    console.log("Failure", err.message);
  }
}

const result = fetchData();

However, I'm having trouble extracting values from result, which contains a Promise object:

Promise { <state>: "pending" }
​
<state>: "fulfilled"
​
<value>: Array [ (95) […] ]

I'm trying to extract the values from: <value>: Array [ (95) […] ]. How do I do so? Is my current approach incorrect?

mmz
  • 1,011
  • 1
  • 8
  • 21
  • 1
    You are using `async` in a slightly strange manner-- you should either `await` the `fetchData()` call or you should chain a `.then` on the promise object and do whatever you need with the result in a callback. – Alexander Nied Aug 25 '21 at 18:38
  • 1
    Since the question is in the context of React, you can't await inside the render phase, so take a look at: [Using async/await inside a React functional component](https://stackoverflow.com/questions/57847626/using-async-await-inside-a-react-functional-component) – Emile Bergeron Aug 25 '21 at 18:48

2 Answers2

1

Change const result = fetchData(); into const result = await fetchData();

Praveen Tamil
  • 1,076
  • 11
  • 22
  • Already tried that and getting this error: `Module parse failed: Cannot use keyword 'await' outside an async function (36:15)`. I'm using React and this is outside a component. Doing so inside a component gets me this error: `Unexpected reserved word 'await'`. – mmz Aug 25 '21 at 18:41
1

You can do

async function fetchData() {
  try {
    var params = { Key: { chart_name: "cambridge_rent" }, TableName: "charts" };
    const data = await docClient.get(params).promise();
    return data.Item.values;
  } catch (err) {
    console.log("Failure", err.message);
  }
}

    fetchData().then((resp) => console.log(resp));