如何解决从Seuquelize返回,然后使用JavaScript中的代码块
我正在尝试从Sequelize的then块返回一个元素数组,但是输出是不可预测的。它的[object Promise]。
这是我试图运行的代码。
const trips = ServiceProviderTrip.findAll({
where: { locationId: location,userId: UserID },})
.then((result2) => {
//TODO: to get the tripid of those locationid having same
const trips = [];
const json2 = result2;
for (var i = 0; i < json2.length; i++) {
var obj = json2[i];
var tripId = obj.tripID;
trips.push(tripId);
}
return trips
})
.catch((error) => {
console.log(red.inverse.bold(error))
});
console.log(chalk.yellow.inverse.bold(trips))
输出为:
[object Promise]
但是我想要的是:
[1,2,3,4]
在此先感谢您对我的解决和帮助。 JS之神。
解决方法
这是因为trips
变量未等待结果。
您的代码是同步的
const trips = ServiceProviderTrip.findAll({
where: { locationId: location,userId: UserID },}).then((result2) => {
//TODO: to get the tripid of those locationid having same
const trips = [];
const json2 = result2;
for (var i = 0; i < json2.length; i++) {
var obj = json2[i];
var tripId = obj.tripID;
trips.push(tripId);
}
return trips
}).catch((error) => {
console.log(red.inverse.bold(error))
});
// If you want to get result here you have to write Asynchronous code
console.log(chalk.yellow.inverse.bold(trips))
编写这样的异步代码:
const getTrips = async ()=>{
const trips = await ServiceProviderTrip.findAll({
where: { locationId: location,}).then((result2) => {
//TODO: to get the tripid of those locationid having same
const trips = [];
const json2 = result2;
for (var i = 0; i < json2.length; i++) {
var obj = json2[i];
var tripId = obj.tripID;
trips.push(tripId);
}
return trips
}).catch((error) => {
console.log(red.inverse.bold(error))
});
console.log(chalk.yellow.inverse.bold(trips))
}
getTrips()
或者您可以在trips
中获得.then
的值-
ServiceProviderTrip.findAll({
where: { locationId: location,}).then((result2) => {
//TODO: to get the tripid of those locationid having same
const trips = [];
const json2 = result2;
for (var i = 0; i < json2.length; i++) {
var obj = json2[i];
var tripId = obj.tripID;
trips.push(tripId);
}
console.log(chalk.yellow.inverse.bold(trips))
}).catch((error) => {
console.log(red.inverse.bold(error))
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。