javascript - 承诺解决对象给空对象
问题描述
所以在我的节点文件中,我从 Mongoose 数据库中获取一些数据,执行一些操作,最后我想要一个像对象一样的字典。现在我的 Mongoose 数据库只有两个我想要的对象,所以我使用aggregate
命令给我那些。然后,我遍历结果,并将它们添加到字典中。然后,我想从字典中显示一些东西。由于这一切的异步性质,我被迫学习/使用 Promise。因此,这是我生成的代码:
function f1(){
return new Promise(resolve=>{
collectionName.aggregate([
{
$group:
{
_id: "$ids",
property: {$max: "$properties"}
}
}
]).then(data=>{
for(i=0; i<data.length; i++){
dictionary[data[i]['_id']] = data[i]['property'];
}
});
resolve(dictionary);
});
};
async function f2(){
var dict = await f1()
console.log(dict)
f1();
f2();
当我将 console.log 放入 for 循环时,我得到了我想要的数据,因为它具有字典形式的 id 和属性。但是,当我运行 f2 时,我只得到{}
输出。有谁知道为什么?
解决方案
由于在resolve(dictionary)
' aggregate()
s之外then()
,它在填充之前执行dictionary
,因此是空对象。尝试将to 移到ofresolve(dictionary)
内部,以返回值为 的承诺。实际上,您正在尝试链接 promises。确保也将整体返回,以确保从 . 中返回整个承诺。then()
aggregate()
dictionary
collectionName.aggregate()
f1()
function f1() {
return new Promise(resolve => {
return collectionName.aggregate([{
$group: {
_id: "$ids",
property: {
$max: "$properties"
}
}
}]).then(data => {
for (i = 0; i < data.length; i++) {
dictionary[data[i]['_id']] = data[i]['property'];
}
return resolve(dictionary);
});
});
}
希望这会有所帮助!
推荐阅读
- kubernetes - 用jsonpath提取kubernetes注解信息
- python - 根据特定列查找两个 python 数据帧的差异
- swift - 调试/检查器/导航器的显示和隐藏按钮在 Xcode 工具栏中消失或重新定位
- sql - 不会出现在最终结果中的 SQL 总和记录
- perl - 使用 conda 和 App::cpanminus 安装 Perl 模块
- embedded - 关于 ISR 期间中断的问题
- python - 我可以在数据框中获取一系列重复字符的索引吗
- python - 定位 Python 的有效负载
- cmake - FindGlew 模块无法找到 glew 库
- haskell - Servant 中的自定义组合器