如何将Promise.all多接口请求结果传递至Handlebars视图?
问题:Promise.all请求结果无法在Handlebars视图中渲染
使用Promise.all发起两个GET请求,请求功能正常,结果可在终端打印,但无法在Handlebars视图中获取这两个请求的结果。
路由代码
router.get("/chart", ensureAuth, function (req, res) { res.render("chart"); }); router.get("/multiple", ensureAuth, function (req, res, next) { const apiRequest1 = fetch( "https://financialmodelingprep.com/api/v3/quote/REFR?apikey=" ).then(function (response) { return response.json(); }); const apiRequest2 = fetch( "https://financialmodelingprep.com/api/v3/quote/XOM?apikey=" ).then(function (response) { return response.json(); }); Promise.all([apiRequest1, apiRequest2]) .then(function (data) { var firstAPI = data[0]; var secondAPI = data[1]; var combinedData = { firstAPI, secondAPI }; console.log(combinedData); res.render('multiple', { combinedData }) }) .catch(function (error) { console.log("Looks like there was a problem: ", error); }); });
请求返回数据
{ "firstAPI": [ { "symbol": "REFR", "name": "Research Frontiers Incorporated", "price": 1.92, "changesPercentage": -2.5381, "change": -0.05, "dayLow": 1.795, "dayHigh": 2, "yearHigh": 2.24, "yearLow": 0.9, "marketCap": 64354176, "priceAvg50": 1.5046, "priceAvg200": 1.23735, "exchange": "NASDAQ", "volume": 107372, "avgVolume": 52760, "open": 1.98, "previousClose": 1.97, "eps": -0.06, "pe": -32, "earningsAnnouncement": "2024-08-01T04:00:00.000+0000", "sharesOutstanding": 33517800, "timestamp": 1715976000 } ], "secondAPI": [ { "symbol": "XOM", "name": "Exxon Mobil Corporation", "price": 119.64, "changesPercentage": 1.5017, "change": 1.77, "dayLow": 117.96, "dayHigh": 119.83, "yearHigh": 123.75, "yearLow": 95.77, "marketCap": 536696665200, "priceAvg50": 116.928, "priceAvg200": 108.89025, "exchange": "NYSE", "volume": 14951304, "avgVolume": 18239392, "open": 118.3, "previousClose": 117.87, "eps": 8.16, "pe": 14.66, "earningsAnnouncement": "2024-07-26T04:00:00.000+0000", "sharesOutstanding": 4485930000, "timestamp": 1715976184 } ] }
错误的视图代码尝试
{{#each combinedData}} <li>{{firstApi.price}}</li> {{/each}}
另一种尝试:
{{#each combinedData.firstApi}} <li>{{price}}</li> {{/each}}
解决方案
问题核心原因有两个:
- 变量名大小写不匹配:路由中传递的是
firstAPI(大写结尾),视图里写成了firstApi(小写结尾),Handlebars对变量名大小写敏感。 - 数据结构是数组:
firstAPI和secondAPI都是包含单个对象的数组,需先访问数组元素才能获取内部属性。
正确的视图写法示例
直接访问数组第一个元素的属性
<!-- 显示REFR的价格 --> <li>{{combinedData.firstAPI.[0].price}}</li> <!-- 显示XOM的价格 --> <li>{{combinedData.secondAPI.[0].price}}</li>
使用each遍历数组(适合多数据项场景)
<!-- 遍历firstAPI数组 --> {{#each combinedData.firstAPI}} <li>{{symbol}}: {{price}}</li> {{/each}} <!-- 遍历secondAPI数组 --> {{#each combinedData.secondAPI}} <li>{{symbol}}: {{price}}</li> {{/each}}
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

