Return 来自 Seuquelize,然后是 JavaScript 中的代码块

Return From Seuquelize then block of code in JavaScript

我正在尝试 return 来自 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, 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))
}

getTrips()

或者您可以在 .then -

中获取您的 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);
    }
    console.log(chalk.yellow.inverse.bold(trips))
}).catch((error) => {
    console.log(red.inverse.bold(error))
});