我正在使用Sequelize,但无法记录promise的值。我正在做console.log('helooo', timekeep);
,但它会打印Promise { <pending> }
。我不知道我是否做对了。
这是我的代码:
const create = async function(req, res) {
res.setHeader('Content-Type', 'application/json');
let err, orders, wallet;
let orders_info = req.body;
console.log('order_info : <<<<<< ' + JSON.stringify(orders_info));
var timekeep = Orders.findAndCountAll(
{
where: {
cid : orders_info.cid,
},
order: [
['id', 'DESC']
],
limit: 1,
}
)
.then(result => {
console.log('hello', result);
console.log(result.count);
console.log(result.rows);
});
console.log('helooo', timekeep);
}
登录变量时,我会得到这样的提示。
helooo
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined }
答案 0 :(得分:0)
timekeep
是您从then
子句返回的值,即Promise<void>
,因为它没有返回值。
使用result
打印的console.log('hello', result);
具有您从Promise中获得的价值。
答案 1 :(得分:0)
我可以看到您的create
函数已经是async
函数。因此,不要使用Promise语法,而应使用async / await语法。现在,您正在尝试将查询表达式分配给变量timekeep
。这是示例代码,
const create = async function (req, res) {
res.setHeader('Content-Type', 'application/json');
let err, orders, wallet;
let orders_info = req.body;
console.log('order_info : <<<<<< ' + JSON.stringify(orders_info));
// try resolving promise
try {
var timekeep = await Orders.findAndCountAll(
{
where: {
cid: orders_info.cid,
},
order: [
['id', 'DESC']
],
limit: 1,
}
);
console.log("RESULT => ", timekeep)
} catch (err) {
// catch error here
console.log(err)
}
}
答案 2 :(得分:-1)
返回数据和async await
概念存在一些小问题,请在下面的代码中添加注释:
var timekeep = await Orders.findAndCountAll({ // <----------- you need add await
where: {
cid: orders_info.cid,
},
order: [
['id', 'DESC']
],
limit: 1,
})
.then(result => {
console.log('hello', result);
console.log(result.count);
console.log(result.rows);
return result; // <----------- also need to return the result from here
});
console.log('helooo', timekeep); // <----- Now check the console