最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - asyncawait within Express route - Stack Overflow

programmeradmin1浏览0评论

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

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 wele 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);
  })();
}
Share Improve this question asked Aug 29, 2021 at 14:00 Tom CarielloTom Cariello 1172 silver badges10 bronze badges 1
  • 1 Your loginToApp function doesn't await anything? – Bergi Commented Aug 29, 2021 at 14:40
Add a ment  | 

1 Answer 1

Reset to default 7

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);
  })
}
发布评论

评论列表(0)

  1. 暂无评论