Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda