2

I've written an async function which is able to get a response from an API I've written in Python but I can't get the data into an array which I can then use to update my frontend application.

The code is as follows:

async function postData(URL) {
  let rawResponse = await fetch(URL, {
    method: "Post",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(inputData),
  });
  const data = await rawResponse.json();
  console.log(data);
  return data;
}  

let response1 = postData();
console.log(response1);

let response2 = postData()["returnedData"];
console.log(response2);

The code returns the array I want when I console.log the data variable within the function. However, it returns an array called 'Promise{pending}'* for response1 which contains the desired data but I am not able to manipulate it and returns 'undefined' for response2. What am I doing wrong?

Thanks in advance!

*pending even though the PromiseState is 'fulfilled'

1 Answer 1

2

PostData Function is a aync Function so returns a Promise so you must use await before calling it or .then

async function postData(URL) {
  let rawResponse = await fetch(URL, {
    method: "Post",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(inputData),
  });
  const data = await rawResponse.json();
  console.log(data);
  return data;
}
// Method 1
const init = async () => {
  let response1 = await postData();
  console.log(response1);

  let response2 = await postData()["returnedData"];
  console.log(response2);
}
init();
// Method 2
(async () => {
  let response1 = await postData();
  console.log(response1);

  let response2 = await postData()["returnedData"];
  console.log(response2);
})()
 

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for your answer! What do I need to do to be able to manipulate the responses outside of a function?
What you can do is to declare a let variable outside init function and reassign it in the init function
When I use this code I still got a promise showing in the console window: const init = async () => { let data = await postData(); return data; }; let data = init(); console.log(data);
Yes Becoz init is async function Try This let data; const init = async () => { data = await postData(); return data; }; init(); console.log(data)
The data variable is still showing as a promise using this method unfortunately
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.