1

I'm trying to await for this API call to complete before sending it to the client in an express route. I have provided the entire route below. The API call returns the required data but I can't get the data outside of the .get function.

    let getAgents = async () => {
        let agents = await httpntlm.get({
            url: `http://localhost:8080/api/agents?PageNumber=${req.params.pageNumber}&PageSize=${req.params.pageSize}`,
            username: 'xxxx',
            password: 'xxxx',
            domain: 'xxxx',
            workstation: 'xxxx',
        }, function(err, res){
            return res.body;
        })
    }
    let data = getAgents().then(res => return res);
    return res.json(data);
})
  • What makes you think that `httpntlm.get` returns a promise? – Quentin May 12 '20 at 21:16
  • @Quentin `async` functions by definition always wrap their output in a Promise. The issue here appears to be that the function neds to `return agents` but doesn't. – Robin Zigmond May 12 '20 at 21:16
  • The async function's returned promise resolves to undefined. And `data` is a promise. But anyhow you are still expecting to get the data synchronously. You order a pizza online and are surprised that your plate is still empty. – trincot May 12 '20 at 21:17
  • @RobinZigmond — I asked about `httpntlm.get`, not `getAgents` … but that would be another problem. – Quentin May 12 '20 at 21:17
  • also: `then(res => return res)` is not doing much useful. – trincot May 12 '20 at 21:19
  • @Quentin it doesn't, it expects a callback function but that part is working. I am trying to use async/await to wait for the results but whenever i console log the results of getAgents() it shows pending or undefined. the agents variable can be ignored.. the reason I'm not returning it is because it also shows undefined – Sean Hufnagel May 12 '20 at 21:25
  • @trincot so how do I wait for the pizza? lol – Sean Hufnagel May 12 '20 at 21:27
  • It is all explained in the referenced Q&A. You can only have the result in a `then` callback or after an `await` inside an `async` function. Because those pieces of code execute later, when the pizza is delivered. – trincot May 13 '20 at 05:39

0 Answers0