solution : not using forEach with a function which need to await for. using a simple for and adding await to the funcion.
I have a mongoose schema :
const TopicSchema = new mongoose.Schema({
name: {type:String,unique:false},
sub_topic:[{type:mongoose.Schema.Types.ObjectId, ref : 'Topic'}]
});
each topic may have subtopics. I want to find for a given topic all of its sub and its sub-sub topic IDs. I wrote a recursive function to search deeper every time and retrive more subs.
Data now is : A-->
B-->no subs
C-->C1,C2
D-->D1,D2,D3
the recursive function:
async function getSubs(ID) {
let subs = [];
const topic = await Topic.findById(ID);
console.log('-------in topic', topic.name)
if (topic.sub_topic.length == 0) {
//stop condition-no more subs just return array with id
return [ID];
}
topic.sub_topic.forEach(function (sub) {
subs.push(sub._id); //add current sub id to array
var data = getSubs(sub._id)
.then((data) => {
subs = subs.concat(getSubs(data));
});
})
return subs; //finally return all found subs
}
and this is how i invoke it :
app.get('/api/topic/subs/:id', (req, res, next) => {
let subs;
subs = getSubs(req.params.id)
.then((subs) => {
console.log('returned subs', subs)
});
});
the problem is the function returns the subs but not waiting for all of the recursive calls to complete their job of adding more subs. this is the output :
-------in topic A
returned subs [ 5bcb558ba68fb623e4d97ae1,
5bcb558ba68fb623e4d97ae4,
5bcb558ca68fb623e4d97ae5 ]
-------in topic C
-------in topic B
-------in topic D
-------in topic C1
-------in topic C2
-------in topic D2
-------in topic D1
...
...and so on
how can i make it wait for the other calls to finish?
-Thank you!