I've got the following problem:
exports.displayArea = (area_id) => { console.log(area_id); return client.query(`SELECT * FROM areas WHERE area_id = ${area_id}`).then(({ rows, rowCount }) => { let newInfo = rows[0]; newInfo.restaurants = client.query(`SELECT * FROM rated_restaurants WHERE area_id = ${area_id}`).then(({ rows }) => { return rows; }); newInfo.total_restaurants = rowCount; return newInfo; }); };
I'm trying to return the second query however it gives me a Promise { }. How do I go about returning two of these?
{
area_id: 2,
area_name: 'Knutsford',
restaurants: Promise { <pending> },
total_restaurants: 1
}
It should ultimately look like this:
{
area_id: 3,
name: 'Picadilly',
total_restaurants: 2,
restaurants: [
{
restaurant_id: 12,
area_id: 3,
name: 'Carluccio’s',
cuisine: 'Italian',
website: 'http://www.carluccios.com/'
}
]
}
Many thanks,
If I understood. you ran two queries, and the end result is a Promise pending type of thing. OKI look
you do not wait for this promise to resolve
newInfo.restaurants = client
.query(`SELECT * FROM rated_restaurants WHERE area_id = ${area_id}`)
.then(({ rows }) => {
return rows;
});
exports.displayArea = (area_id) => {
console.log(area_id);
let newInfo
return client
.query(`SELECT * FROM areas WHERE area_id = ${area_id}`)
.then(({ rows, rowCount }) => {
newInfo = rows[0];
newInfo.total_restaurants = rowCount;
return client
.query(`SELECT * FROM rated_restaurants WHERE area_id = ${area_id}`)
.then(({ rows }) => {
newInfo.restaurants = rows;
return newInfo;
});
});
};
How about the following:
exports.displayArea = (area_id) => {
console.log(area_id)
var q1 = client
.query(`SELECT * FROM areas WHERE area_id = ${area_id}`)
.then(({ rows, rowCount }) => {
return [rows, rowCount]
})
var q2 = client
.query(`SELECT * FROM rated_restaurants WHERE area_id = ${area_id}`)
.then(({ rows }) => {
return rows
})
return Promise.all([q1, q2]).then(function ([resultQ1, resultQ2]) {
let newInfo = resultQ1[0][0]
newInfo.restaurants = resultQ2
newInfo.total_restaurants = resultQ1[1]
return newInfo
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.