Reputation: 5
I'm new at Node and what I'm trying to do here is call a function before the page rendered but my functions work after my page rendered and I can't get data coming from another function.
exports.getCity = (req, res) => {
controlCity(req.params.city).then((control) => {
res.render('index.ejs', control);
})
}
const controlCity = async (cityStub) => {
return new Promise((resolve, reject) => {
City.findAll({ where: { SEHIRSTUB: cityStub } })
.then(
city => {
if (city.length === 0) { // when it comes here it works
resolve({ value: "test" });
}
else {
resolve(controlPredictedWeather(city[0]));
}
}).catch(err => console.log(err));
}
)
}
const controlPredictedWeather = city => {
Predicted_Weather.findAll({ where: { CITYID: city.ID } }).then(
degree => {
if (degree.length === 0) {
return (getPredictedWeather(city)); // it goes another function
}
else {
console.log({ value: degree[0], city: city });
return { value: degree[0].degree, city: city };
}
}
).catch(err => console.log(err))
}
How can I solve this problem?
Upvotes: 0
Views: 49
Reputation: 1
The issue is that you don't return anything in controlPredictedWeather
function
const controlPredictedWeather = city => {
// vvv added return here
return Predicted_Weather.findAll({ where: { CITYID: city.ID } }).then(
degree => {
if (degree.length === 0) {
return (getPredictedWeather(city)); // it goes another function
}
else {
console.log({ value: degree[0], city: city });
return { value: degree[0].degree, city: city };
}
}
).catch(err => console.log(err))
}
Having solved the issue, now you can address the elephant in the room
async
function with no await
new Promise
where it's never requiredSince you have used async
keyword, that suggests you want to use the somewhat easier to read async
/await
pattern of using Promises
So, why not use it fully
Like this
exports.getCity = async (req, res) => {
const control = await controlCity(req.params.city);
res.render('index.ejs', control);
};
const controlCity = async (cityStub) => {
try {
const city = await City.findAll({ where: { SEHIRSTUB: cityStub } });
if (city.length === 0) { // when it comes here it works
return { value: "test" };
}
// no need for else since returning above
return controlPredictedWeather(city[0]);
} catch(err) {
console.log(err);
}
};
const controlPredictedWeather = async (city) => {
try {
const degree = await Predicted_Weather.findAll({ where: { CITYID: city.ID } });
if (degree.length === 0) {
return (getPredictedWeather(city)); // it goes another function
}
// no need for else since returning above
console.log({ value: degree[0], city: city });
return { value: degree[0].degree, city: city };
} catch(err) {
console.log(err)
}
};
Of course, there is one elephant left in the room, and that is that control
in
res.render('index.ejs', control);
WILL be undefined
if either of .findAll
s throw an error - this will also be the case in your original code, just thought I'd mention that
Upvotes: 1