简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM