Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
async/await within Express route

I have a node/express route that collects information via url parameters. I use these parameters to initiate a separate function which takes a few seconds. I am trying async/await to wait for the function to return data but the route logic just plows ahead, not waiting for anything.

Is this a syntax/structure problem? Any tips are welcome as I seem to have hit a wall. Thanks!

app.get('/testlogin', (req, res) => {
  (async () => {
    // This needs to wait until loginToApp returns data but it does not
    await loginToApp(req.query.u, req.query.p)
       .then((data) => {
        console.log('from testlogin route. This should print after loginToApp');
        console.log(data); // the returned data
      });
  })();
});

async function loginToApp(user, pwd) {
  (async () => {
    setTimeout(() => {
      const data = { temp: 1, rtemp: 2 };
      console.log('from loginToApp');
      console.log(data);
      return data;
    }, 2000);
  })();
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Your loginToApp function needs to return a Promise for you to await. If using a setTimeout, then you'll have to explicitly wrap it in a new Promise.

app.get('/testlogin', async (req, res) => {
  const data = await loginToApp(req.query.u, req.query.p);
  console.log(data);
});

async function loginToApp(user, pwd) {
  return new Promise(res => {
    setTimeout(() => {
      const data = { temp: 1, rtemp: 2 };
      console.log('from loginToApp');
      console.log(data);
      res(data);
    }, 2000);
  })
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!