后续查询 returns Promise。如何等待查询到 return 结果?
Sequelize query returns Promise. How to wait for query to return result?
我有两个模型具有 User
belongsTo Status
关系。我正在尝试跟踪对 User
记录中的 status
列所做的更改。我的钩子里有:
afterUpdate: (instance, options) => {
if (instance.dataValues.statusId !== instance._previousDataValues.statusId){
const Track = {
new_status: sequelize.models.Status.findById(instance.dataValues.statusId).then(status => {
console.log('1._____');
console.log(status.dataValues.name);
return status.dataValues.name;
})
}
console.log('2.____');
console.log(Track.new_status);
} else{
console.log('Status is not changed');
}
}
输出:
2.____
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined }
Executing (default): SELECT "id", "name", "detail", "createdAt", "updatedAt" FROM "Statuses" AS "Status" WHERE "Status"."id" = 18;
1._____
Cancelled
我在 console.log(Track.new_status)
看到查询尚未完成,在 console.log(status.dataValues.name)
它正确地 returns 状态名称。如何让它等到查询完成?
使用async/await
:
async function getTrack(trackID) {
const track = await Track.findByPk(trackID);
console.log('track', track);
}
使用承诺:
function getTrack(trackID) {
const track = Track.findByPk(trackID)
.then((track) => {
console.log('track', track);
});
}
我有两个模型具有 User
belongsTo Status
关系。我正在尝试跟踪对 User
记录中的 status
列所做的更改。我的钩子里有:
afterUpdate: (instance, options) => {
if (instance.dataValues.statusId !== instance._previousDataValues.statusId){
const Track = {
new_status: sequelize.models.Status.findById(instance.dataValues.statusId).then(status => {
console.log('1._____');
console.log(status.dataValues.name);
return status.dataValues.name;
})
}
console.log('2.____');
console.log(Track.new_status);
} else{
console.log('Status is not changed');
}
}
输出:
2.____
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined }
Executing (default): SELECT "id", "name", "detail", "createdAt", "updatedAt" FROM "Statuses" AS "Status" WHERE "Status"."id" = 18;
1._____
Cancelled
我在 console.log(Track.new_status)
看到查询尚未完成,在 console.log(status.dataValues.name)
它正确地 returns 状态名称。如何让它等到查询完成?
使用async/await
:
async function getTrack(trackID) {
const track = await Track.findByPk(trackID);
console.log('track', track);
}
使用承诺:
function getTrack(trackID) {
const track = Track.findByPk(trackID)
.then((track) => {
console.log('track', track);
});
}