简体   繁体   English

使用 Express JS app.get 以及 Promise pending inside

[英]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'.我正在尝试在名为“get_stock_data”的 nodejs 服务器中实现 api 路由。 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 <>.目前,如果我尝试记录响应,它会显示 Promise <>。 Im not sure how I would add.then() and wait for the promise.我不确定我将如何添加.then() 并等待 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. get_stock_data_request 是一个异步/等待 function,它调用 nodejs 上的 API 库。

You can use async/await for request handler as well (it's also just normal function;-) .您也可以将async/await用于请求处理程序(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只需使用thencatch来处理来自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));也许尝试添加await以便await res.send(get_stock_data_request(stockName)); if not try adding res.send(await get_stock_data_request(stockName));如果没有尝试添加res.send(await get_stock_data_request(stockName));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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