函数内部的函数不等待javascript中的承诺

编程入门 行业动态 更新时间:2024-10-26 10:27:37
本文介绍了函数内部的函数不等待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中的承诺

本文发布于:2023-11-06 09:57:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563379.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!