繁体   English   中英

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

[英]Using Express JS app.get along with Promise pending inside

我正在尝试在名为“get_stock_data”的 nodejs 服务器中实现 api 路由。 但是,一旦使用此路由,服务器就会调用另一个库来获取数据,并作为回报将其发回。 目前,如果我尝试记录响应,它会显示 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));
}
);

get_stock_data_request 是一个异步/等待 function,它调用 nodejs 上的 API 库。

您也可以将async/await用于请求处理程序(it's also just normal function;-)

试试这样:

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

只需使用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')
    }
}
);

也许尝试添加await以便await res.send(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