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

235
Visualizações
How would I go about converting a function that uses fetch calls to async/await?

How would I go about converting this to use async/await instead of fetch? Sorry, I'm really confused on the subject and would really appreciate some help.

coreHTTP.prototype.post = (url, data) => {
  return new Promise((resolve, reject) => {
    fetch(url, {
      method: "POST",
      headers: {"content-type": "application/json"},
      body: JSON.stringify(data)
    })
      .then(res => res.json())
      .then(data => resolve(data))
      .catch(err => reject(err));
  });
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

How bout leaving the fetch as it is? If you just want to use awaits than there's no problem with it being there.

coreHTTP.prototype.post = async (url, data) => {
    const responseData = await fetch(url, {
      method: "POST",
      headers: {"content-type": "application/json"},
      body: JSON.stringify(data)
    });

    const responseJson = await responseData.json();
    return responseJson;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You can try to remember it like this. JS uses asynchronous coding right, so we do that using promises. One way is as you see it in your question where you call for a resource(fetch in this case) and we wait for the resource modification using .then and .catch .

Similarly, for async/await the logic is the same except syntax is a bit different. First of all to use await inside any function we have to first define the function as async and then you just use await ahead of any function you use inside that. You can also use try/catch to deal with errors better. Let me know if you need help understanding more. I am new to this comments section so I dont know how to exactly attach code snippets but I will attach a screenshot for now for your reference.

Async/await

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