函数内部的函数不等待javascript中的承诺 [英] function inside function is not waiting for promise in javascript
问题描述
对不起,如果我的标题不是很明确,我不知道该如何正确解释.我正在尝试为使用环回3和mongodb的应用程序使用独特的功能.它似乎工作正常,但是我的端点不会在函数内部命中返回值.这是我的代码
Sorry if my title is not very explicit I dont know how to explain this properly. I am trying to use the distinct function for my app that uses loopback 3 and mongodb. It seems to work right but my endpoint wont hit the return inside my function. This is my code
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 []的注释,它将发送返回信息,稍后它将显示应该是最后一个,因此即使我没有返回信息,它也似乎完成了.现在正在等待响应.我不喜欢我的代码的外观,因此,如何使它看起来更好的任何指针,我都会接受.
If I uncomment the return [] it will send the return and later it will show the should be last, so even when I dont have the return it seems to finish. It is now waiting for the response. I dont like the way my code looks so any pointer of how to make this look better I will take it.
推荐答案
看起来 sellerCollection.distinct
将回调作为其参数之一,因此,您不能>将 async/await
与回调样式函数一起使用,因为这不是承诺.
It looks like the sellerCollection.distinct
takes a callback as one of it's parameters, therefore, you cannot use async/await
with a callback-style function, since it's not a promise.
如果您想使用 async/await
:
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
一起使用,例如:
Then, you can use this new function with async/await
like such:
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中的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!