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

216
Visualizações
Is it possible to make this code use await/async rather than promises?

I have this existing function, which works fine:

const fetchWrapper = (resource, init) => {
  console.log('About to fetch...', resource)
  const p = fetch(resource, init)

  p.then(
    (response) => {
      console.log('The response is:', response)
    },
    (error) => {
      console.log('The error is:', error)
    }  
  )
  return p
}

I try to use async/await whenever possible. However, I am thinking that it's not actually possible to do so. The main issue is that I want to return the promise returned by fetch(), so that the calling function can await as it would normally do.

But I also want extra things to happen just before calling fetch() (that's the easy part) and then straight after a network response.

To do that, I am attaching two callback (response and error) to the promise returned by fetch().

If I were not to use promises, I would have to await for the fetch() call -- but then the caller won't receive the response till the promise is resolved, which is not what I want.

So... is it even possible to convert this code to full async/await?

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

0

The code below, which uses async and await, does the same thing as your code:

// A simple promise response
const mockFetch = async (resource, init) => 'Response'

const fetchWrapper = async (resource, init) => {
    console.log('About to fetch...', resource)

    // You'll replace 'mockFetch' with 'fetch'
    const p = mockFetch(resource, init);

    // You can use a named function instead
    (async () => {
        try {
            const response = await p
            console.log('The response is:', response)
        } catch (error) {
            console.log('The error is:', error)
        }
    })()

    return p
}

(async () => {
    const response = await fetchWrapper('', {})
    console.log(response)
})()

mockFetch is for demonstration purpose, you'll need to remove and replace const p = mockFetch(resource, init); with const p = fetch(resource, init);

about 4 years ago · Juan Pablo Isaza Relatório

0

Maybe something like this:

const fetchWrapper = async (resource, init) => {
  try {
    const response = await fetch(resource, init);
    console.log('The response is:', response);
    return { success: true, response };
  } catch(error) {
    console.log('The error is:', error);
    return { success: false, error };
  }
}

about 4 years ago · Juan Pablo Isaza Relatório

0

For ommiting usage of .then() / .catch() you could go with this:

const fetchWrapper = (resource, init) => {

    // do stuff before fetch here ^^ 
    // ...

    // call the fetch
    const p = fetch(resource, init)

    const afterFetchEffects = async () => {

        // since it is "detached" (i call it like so..) 
        // you should ofc use try/catch
        try {

            // wait for the fetch() to finish
            await p

            // do some stuff after fetch
            // ... 
    
        } catch(err) {
            console.error('Error in detached after fetch promise..', err)
        }
    }

    // execute the wrapper which executes something after the fetch..
    // do not await it then it will do its own business.
    afterFetchEffects()

    // pass fetch immediatly back
    return p

}

I am not sure which approach is more readable^^

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