抱歉,如果我的标题不是很明确,我不知道如何正确解释这一点。 我正在尝试为我的使用 Loopback 3 和 mongodb 的应用程序使用不同的函数。它似乎工作正常,但我的端点不会在我的函数内返回。 这是我的代码
const distinctUsers = await sellerCollection.distinct('userId',{
hostId : host.id,
eventId:{
"$ne" : eventId
}
}, async function (err, userIds) {;
if(!userIds || userIds.length ==0)
return [];
const filter = {
where:{
id: {
inq: userIds
}
}
};
console.log("should be last")
return await BPUser.find(filter);
});
console.log(distinctUsers);
console.log("wtf??");
//return [];
如果我取消注释 return [] ,它将发送返回值,稍后它将显示应该是最后一个,所以即使我没有返回值,它似乎也完成了。现在正在等待答复。我不喜欢我的代码的外观,因此任何有关如何使其看起来更好的指示我都会接受。
最佳答案
看起来sellerCollection.distinct
将回调作为其参数之一,因此,您不能将async/await
与回调风格的函数,因为它不是一个 promise 。
如果您想使用async/await
,我建议将此调用转变为 promise :
function findDistinct(hostId, eventId) {
return new Promise((resolve, reject) => {
sellerCollection.distinct(
'userId',
{ hostId, eventId: { "$ne": eventId } },
function (error, userIds) {
if (error) {
reject(error);
return;
}
if (!userIds || userIds.length === 0) {
resolve([]);
return;
}
resolve(userIds);
}
)
})
}
然后,您可以将这个新函数与 async/await
一起使用,如下所示:
async function getDistinctUsers() {
try {
const hostId = ...
const eventId = ...
const distinctUsers = await findDistinct(hostId, eventId)
if (distinctUsers.length === 0) {
return
}
const filter = {
where: {
id: { inq: userIds }
}
}
const bpUsers = await BPUser.find(filter) // assuming it's a promise
console.log(bpUsers)
} catch (error) {
// handle error
}
}
关于javascript - 函数内部的函数不等待 JavaScript 中的 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57486664/