Node.js 异步等待与承诺所有
我想知道我是否正确使用了promise.all和async Wait 基本上,我需要根据ID获取房屋数据,然后我需要获取该房屋的所有评论以及评论数量Node.js 异步等待与承诺所有,node.js,async-await,sequelize.js,Node.js,Async Await,Sequelize.js,我想知道我是否正确使用了promise.all和async Wait 基本上,我需要根据ID获取房屋数据,然后我需要获取该房屋的所有评论以及评论数量 server.get("/api/houses/:id", async (req, res) => { const { id } = req.params; const house = await House.findByPk(id); if (!house) { return res.status(4
server.get("/api/houses/:id", async (req, res) => {
const { id } = req.params;
const house = await House.findByPk(id);
if (!house) {
return res.status(400).send("No house found");
}
const reviews = await Review.findAndCountAll({
where: {
houseId: house.id
}
});
house.dataValues.reviewsCount = reviews.count;
const results = await Promise.all([house.dataValues, reviews.rows]);
console.log(results);
res.send(results);
});
在前端,当我在发出http请求后记录console.log响应时,我会返回下面的内容,因为Promise.all提供了数组。但我不知道这是最好的方法还是有更好的方法
[
{
id: 2329,
host: 2,
picture: '/img/houses/1.jpg',
type: 'Entire house',
town: 'Some town',
title: 'Some title',
price: 50,
description: 'Some description',
guests: 4,
bedrooms: 1,
beds: 2,
baths: 1,
wifi: true,
reviewsCount: 2
},
[
{
id: 1,
houseId: 2329,
userId: 1,
comment: 'An awesome review',
createdAt: '2019-01-11T22:00:00.000Z',
updatedAt: '2019-01-11T22:00:00.000Z'
},
{
id: 2,
houseId: 2329,
userId: 2,
comment: 'Another awesome review',
createdAt: '2019-01-11T22:00:00.000Z',
updatedAt: '2019-01-11T22:00:00.000Z'
}
]
]
您没有正确使用
Promise.all
。代码正在运行,因为您正在分别等待每个承诺
由于Review.findAndCountAll
取决于House.findByPk
结果,Promise.all
在这里没有任何好处
您正在使用Promise.all
和已解析的两个Promise值,所以您可以直接删除它
server.get("/api/houses/:id", async (req, res) => {
const { id } = req.params;
const housePromise = await House.findByPk(id);
const reviews = await Review.findAndCountAll({
where: {
houseId: house.id
}
});
house.dataValues.reviewsCount = reviews.count;
res.send([house.dataValues, reviews.rows]);
});
基本上你在做:
const res = await Promise.all([1, 5]); // [1, 5]
可直接翻译为:
const res = [1, 5];
与其以数组形式发送,不如发送一个对象:
{
house: house.dataValues,
reviews: reviews.rows
}
您可以忽略
async wait
并使用Promise
。您可以尝试以下代码
server.get("/api/houses/:id", async (req, res) => {
const { id } = req.params;
return House.findByPk(id)
.then( house => {
// !house might be 'true' if house is 'undefined'
if( house === undefined || !house ) {
return res.status(400).send("No house found");
}
return Review.findAndCountAll({ where: { houseId: house.id } })
.then(reviews => {
house.dataValues.reviewsCount = reviews.count;
return {house, reviews};
})
.catch(error => res.send(error));
})
.then( result => {
return res.send(results);
})
.catch(error => {
return res.send(error);
});
})
啊,好的。非常感谢。它仍然以数组的形式发回数据,所以说获取
house.dataValues
是正确的吗?例如,我会使用props.house[0]。title
和评论props.house[1]。注释是的,当我在前端获取它时,看起来确实更好!谢谢,但我想使用async/wait