Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

94
Visualizações
Extract response data array from fetch function with post method

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'

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
})()
 

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda