Reputation: 15
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
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
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
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