javascript - JavaScript:带有 Promise 的递归函数,解析返回“未定义”
问题描述
我有一个返回承诺的递归函数,有一些条件会在完成时触发。但是解析总是返回未定义的。
这是代码:
var children = [];
var temp = [];
function getRelationsOfRep(repId) {
var index;
return new Promise(function (resolve, reject) {
return RepRelation.findOne({_id: repId}).then(function (repData) {
if (<condition>) {
temp = temp.concat(repData.children);
temp.forEach(function (childId) {
return getRelationsOfRep(childId);
});
} else {
// else
}
if (<another condition>) {
return resolve(children);
}
}).catch(function (error) {
return reject(error);
})
})
}
function updateRepData(id){
children = [];
temp = [];
getRelationsOfRep(id).then(function (branchesData) {
console.log('branchesData:: ', branchesData); // it prints undefined
})
}
我正在尝试获取代表的所有孩子及其孩子的孩子(如果有的话)并将它们全部归还。
我做错了什么?
任何帮助将非常感激。
提前致谢。
解决方案
使用 Promise.all() 捕获 Loop 中的所有 Promise。
代替:
temp.forEach(function (childId) {
return getRelationsOfRep(childId);
});
尝试:
var promisesArray = [];
temp.forEach(function (childId) {
promisesArray.push(getRelationsOfRep(childId));
});
return Promise.all(promisesArray);
使用这样的东西,您将能够获得递归调用的嵌套响应。
PS 未测试,根据你想要的逻辑修改。
推荐阅读
- internet-explorer - 角度 8 应用程序 UI 未在 IE 中呈现
- c# - LINQ:加入表并返回错误数据
- java - 如果 JSON 响应与 Java 类不匹配会产生错误吗?
- css - CSS Grid 和 Angular:如何制作一个 L 形组件,让空单元格可以被其他组件中的其他元素填充?
- android-studio - iphone可以在不使用标签的情况下直接从android设备读取NFC吗
- html - 图像未覆盖所有屏幕尺寸
- java - 如果我在 recyclerview 中添加 n 个数据,它只显示 n-1 个数据。当我添加第 n+1 个数据时,它显示第 n 个数据
- r - 如何根据 Shiny 中的选择输入调用不同的模块?
- spring-tools-4 - 适用于 Windows 32 位的 Spring Tool Suite 4
- c# - 在 C# MVC 中调用外部 API