我正在设置一个仪表板项目。在这里,我需要一个天气小部件。因此,我创建了一个按城市获取天气的函数。但是我无法在请求函数之外获得该值,因为。我想要它是因为我想将此值存储在数组中并将该数组传递给渲染。 你能帮我吗?
function getWeather(city) {
let apiKey = '48eb9b6228b51e3445b97cb1640729a1'
let url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`
var test = request(url, (err, response, body) => {
if (err) console.log('error:', error)
return body.main.temp
})
return ""
}
router.get('/dashboard', ensureAuthenticated, (req, res) => {
//Get the widgets of the user
var widget
var widgets = {
name: "",
content: "",
value: ""
}
var tabWidgets = []
//
if (req.user.local) {
widget = req.user.local.widgets
} else if (req.user.facebook) {
widget = req.user.facebook.widgets
}
for (var i = 0; i < widget.length; i++) {
if (widget[i].name == "weather") {
widgets.name = widget[i].name
widgets.content = widget[i].content
widgets.value = getWeatherFromCity(widgets.content)
tabWidgets.push(widgets)
} else if (widget[i].name == "youtube") {
continue
} else if (widgets[i].name == "steam") {
continue
}
}
res.render('dashboard', {
user: req.user,
widgets: tabWidgets
})
})