Tom Cariello
Tom Cariello

Reputation: 117

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);
  })();
}

Upvotes: 5

Views: 5345

Answers (1)

Nick
Nick

Reputation: 16576

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);
  })
}

Upvotes: 7

Related Questions