Home > Net >  res.send() is running before async function call on express.js
res.send() is running before async function call on express.js

Time:04-15

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

CodePudding user response:

  • 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
}

CodePudding user response:

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(...).

  • Related