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

117
Vistas
Clearner way to wait for function to complete before continuing

First I fetch a random quote from a public api. Only AFTER I actually have a quote I want to render the page including that quote.

I am a JavaScript newbie so please bear with me if this is a stupid question.

I was struggling with waiting for the api call to return BEFORE continuing with rendering the page. I wanted to do the following, but this doesn't work because res.render will be called before I have a quote. (note: I am using Express and Axios)

async function getRandomQuote() {
    try {
        const res = await axios.get("https://api.quotable.io/random?tags=famous-quotes")
        console.log(`${res.data.content} - ${res.data.author}`)     //This prints fine
        return res.data
    } catch(e) {
        console.log('error', e)
    }
}

app.get('/', (req, res) => {

    const quote = getRandomQuote()
    console.log(`${quote.content} - ${quote.author}`)    //This prints 'undefined' because 'getRandomQuote' isn't finished yet

    res.render('home', { quote })
})

The only way I figured out to do it is as follows, but I find this really messy. Is there a cleaner way to do this? Or do I always need to put all the lines of code that I want to wait for each other in an async function?

async function getRandomQuote() {
    try {
        const res = await axios.get("https://api.quotable.io/random?tags=famous-quotes")
        console.log(`${res.data.content} - ${res.data.author}`)     //This prints fine
        return res.data
    } catch(e) {
        console.log('error', e)
    }
}

app.get('/', (req, res) => {

    const getQuoteAndRender = async() => {
        const quote = await getRandomQuote()
        console.log(`${quote.content} - ${quote.author}`)    //This prints only if I wrap everything in yet another aync function, otherwise it will not wait for 'getRandomQuote' to complete

        res.render('home', { quote })
    }
    getQuoteAndRender()
})

(Note: I realize rendering the page after I successfully get a quote is not ideal either because this means I will not get a page at all if the quote api (for some reason) doesn't work. But for now I just want to know how to do this with the waiting.)

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Heres what you need to do. Make your controller async by doing this app.get('/', async (req, res)

app.get('/', async (req, res) => {

const quote = await getRandomQuote()
console.log(`${quote.content} - ${quote.author}`)    //This prints 'undefined' because 'getRandomQuote' isn't finished yet

res.render('home', { quote })
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this:

getRandomQuote()
.then(quote => {
  console.log(`${quote.content} - ${quote.author}`) 
  res.render('home', { quote })
});
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