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

440
Visualizações
res.send() is running before async function call on express.js

Summary: creating my own API that returns epoch time, and it involves using an express.js server, but it's running res.send() before the function call. I referenced this page, but it didn't help. Here's what I have:

app.get('/timestampAPI', async (req, res,) => {
    try {
        let finalResult  = await getTimeStamp();
        res.send({ something: finalResult });
    } catch (error) {
        console.log(error);
    }
});

It'll start to run the function getTimeStamp(), and before that function finishes, it runs the res.send() function which shows up as '{}' because finalResult doesn't have a value. getTimeStamp() is an async function. I'm unsure of what I'm doing wrong.

Edit: getTimeStamp() function:

async function getTimeStamp() {
    await axios.get('https://showcase.api.linx.twenty57.net/UnixTime/tounixtimestamp?datetime=now')
        .then(response => {
            // also used console.log(response.data.UnixTimeStamp), which returns the timestamp
            return response.data;
        })
        .catch(error => {
            var errorMessage = error.response.statusText;
            console.log(errorMessage);
        });
    }

Another edit: yes, the API referenced above does return the current epoch time, but CORS is blocking my other site from accessing it directly, so I can't use it on that site, which is why I'm using node.js for it so that I can allow myself to access it through my node.js program. Couldn't think of another way

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

  • returning value of the then method does not return from getTimeStamp function you should write you code in resolve pattern or using await like below

try this, make sure you write correct field name in response object

async function getTimeStamp() {
    try{
       const res = await axios.get('https://showcase.api.linx.twenty57.net/UnixTime/tounixtimestamp?datetime=now')
       return res.data
    }catch(error){
      throw error
}
about 4 years ago · Santiago Trujillo Relatório

0

As an alternative to Mohammad's answer you can also use returning getTimeStamp function's result as a promise and it can solve your problem.

async function getTimeStamp() {
return new Promise((resolve, reject) => {
  axios.get('https://showcase.api.linx.twenty57.net/UnixTime/tounixtimestamp?datetime=now')
    .then(response => {
        // also used console.log(response.data.UnixTimeStamp), which returns the timestamp
        resolve(response.data);
    })
    .catch(error => {
        var errorMessage = error.response.statusText;
        console.log(errorMessage);
        reject(error);
    });
})
}

Or you would also replace await with return in getTimeStamp function in your code if you don't want to return promise.(Which is not I recommend.). You should also throw the error in catch block which is generated in getTimeStamp function for catching the error in try-catch block that you use to call app.get(...).

about 4 years ago · Santiago Trujillo 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