Sohaib Asim
Sohaib Asim

Reputation: 15

Using Express JS app.get along with Promise pending inside

I am trying to implement an api route in my nodejs server called 'get_stock_data'. However, once this route is used, the server calls another library to get the data, and in return sends it back. Currently if I try to log the response, it says Promise <>. Im not sure how I would add .then() and wait for the promise.

app.get('/get_stock_data', (req, res) => {
    res.header("Access-Control-Allow-Origin", "*");
    const stockName = JSON.parse(req.query.data).stockName;     
    res.send(get_stock_data_request(stockName));
}
);

The get_stock_data_request is an async/await function that calls API libraries on nodejs.

Upvotes: 1

Views: 1204

Answers (3)

Anatoly
Anatoly

Reputation: 22758

Just use then and catch to process a regular and error responses from get_stock_data_request

app.get('/get_stock_data', (req, res) => {
    res.header("Access-Control-Allow-Origin", "*");
    try {
      const stockName = JSON.parse(req.query.data).stockName;     
      get_stock_data_request(stockName)
       .then(result => res.send(result))
       .catch(err => res.status(400).send(err));
    } catch (err) {
       res.status(400).send('Error parsing query parameters')
    }
}
);

Upvotes: 2

Naren
Naren

Reputation: 4470

You can use async/await for request handler as well (it's also just normal function ;-).

Try like this:

app.get('/get_stock_data', async (req, res) => {
    try {
        res.header("Access-Control-Allow-Origin", "*");
        const stockName = JSON.parse(req.query.data).stockName;
        const response = await get_stock_data_request(stockName)
        return res.json(response) // If you get json as response otherwise use `res.send`
    } catch(err) {
       res.status(400).json(err) or .send(err)
    }
);

Upvotes: 3

destroyer22719
destroyer22719

Reputation: 404

Maybe try adding await so that should be await res.send(get_stock_data_request(stockName)); if not try adding res.send(await get_stock_data_request(stockName));

Upvotes: 0

Related Questions