Traversing and build Tree from fetched child details in NodeJS [duplicate]Using async/await with a forEach loopIs there a way to get version from package.json in nodejs code?best way to get folder and file list in Javascriptcan Promises/A+ promises be leveraged to implement synchronous-when-already-resolved semantics?Return a promise without waiting for a dependant promise in function in nodejsJavascript promise not being returned with async/awaitPromise.all([…]) filling in objectNot able to access returned Promise valueJavaScript Promise with FileReaderAxios.get() inside a map function to get data for multiple objects returning promise objectFastest way of processing a nested tree of promises in javascript?

`microtype`: Set Minimum Width of a Space

Bayes factor vs P value

How to find if a column is referenced in a computed column?

Could moose/elk survive in the Amazon forest?

Complex numbers z=-3-4i polar form

Scheduling based problem

A faster way to compute the largest prime factor

Do I need to watch Ant-Man and the Wasp and Captain Marvel before watching Avengers: Endgame?

What's the difference between using dependency injection with a container and using a service locator?

"Whatever a Russian does, they end up making the Kalashnikov gun"? Are there any similar proverbs in English?

Is Diceware more secure than a long passphrase?

Why did C use the -> operator instead of reusing the . operator?

Find a stone which is not the lightest one

Restricting the options of a lookup field, based on the value of another lookup field?

What does "function" actually mean in music?

Apply a different color ramp to subset of categorized symbols in QGIS?

Why do games have consumables?

Help with my training data

What makes accurate emulation of old systems a difficult task?

Why didn't the Space Shuttle bounce back into space as many times as possible so as to lose a lot of kinetic energy up there?

Are there moral objections to a life motivated purely by money? How to sway a person from this lifestyle?

What is this word supposed to be?

What *exactly* is electrical current, voltage, and resistance?

How to pronounce 'c++' in Spanish



Traversing and build Tree from fetched child details in NodeJS [duplicate]


Using async/await with a forEach loopIs there a way to get version from package.json in nodejs code?best way to get folder and file list in Javascriptcan Promises/A+ promises be leveraged to implement synchronous-when-already-resolved semantics?Return a promise without waiting for a dependant promise in function in nodejsJavascript promise not being returned with async/awaitPromise.all([…]) filling in objectNot able to access returned Promise valueJavaScript Promise with FileReaderAxios.get() inside a map function to get data for multiple objects returning promise objectFastest way of processing a nested tree of promises in javascript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1
















This question already has an answer here:



  • Using async/await with a forEach loop

    13 answers



I am trying to build a tree structure by traversing a given ID and attaching its child to the tree. It always assigns user.children = 'sample' instead of fetched user children from user.children = usrChild, also tried usrArr[index].children = 'sample'



What I am trying to implement:
using a userID, I will fetch its children, now for each children i will fetch their children until there are no children left.



function UserProfile.getUserChildren returns a promise with data consisting of all the children.
Now, we iterate each children and fetch their children



Output Expected Visually:



enter image description here



Programatically What I am expecting:



[

text:
userID: 1
name: 'Mike'
,
children:[

text:
userID: 2
name: 'John'
,
children [

text:
userID: 4
name: 'Hero'
,
children []

]
,

text:
userID: 3
name: 'Kelvin'
,
children []


]

]


Code in Node JS:



let UserProfile = require('./UserProfile');

// Love Dad 83273010
let userID = 51405009;
var allDistributors = Array();
rootUser = new Object();
rootUser.text = userID:userID,name:'Root';
rootUser.children = [];
function getUserTree(userID)
return new Promise( (resolve,reject) =>
/*
* UserDownline Return User child Array
* Format:
* [
* text:
* userID: 45
* name: 'Mike'
* ,
* children:[]
*
* ]
*
*/
UserProfile.getUserChildren(userID).then(async (data) =>
if(data.length > 0)
rootUser.children = data;
/*
* Iterating each user to fetch and assign its child
*/
await rootUser.children.forEach(async (user,index,usrArr) =>

user.children = 'sample'

await getUserTree(user.text.title).then( async(usrChild) =>
/*
Assigning child to root user
*/
usrArr[index].children = usrChild; // STILL NOT ABLE TO ASSIGN VALUE and return user.children as 'sample'
).then(resolve(rootUser));



);
//resolve(rootUser)
//console.log(rootUser)
//return Promise.all(rootUser);
else
resolve([]); // return empty child when no child exist
);
//return rootUser.children;

//console.log(rootUser);
);



//console.log(JSON.stringify(rootUser));
getUserTree(userID).then((data) =>
console.log(JSON.stringify(data));
);









share|improve this question













marked as duplicate by Bergi es6-promise
Users with the  es6-promise badge can single-handedly close es6-promise questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 9 at 12:45


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


















  • await xxx.forEach(async - this does not do what you think it does ... since forEach returns (immediately) undefined, nothing inside the forEach callback is awaited on

    – Jaromanda X
    Mar 9 at 7:53











  • Any idea how can I achieve it or any other way to iterate, so assignment is performed upon completion of getUserTree ?

    – Ashish Patel
    Mar 9 at 10:31











  • Array.map with promise.all

    – Jaromanda X
    Mar 9 at 10:46

















1
















This question already has an answer here:



  • Using async/await with a forEach loop

    13 answers



I am trying to build a tree structure by traversing a given ID and attaching its child to the tree. It always assigns user.children = 'sample' instead of fetched user children from user.children = usrChild, also tried usrArr[index].children = 'sample'



What I am trying to implement:
using a userID, I will fetch its children, now for each children i will fetch their children until there are no children left.



function UserProfile.getUserChildren returns a promise with data consisting of all the children.
Now, we iterate each children and fetch their children



Output Expected Visually:



enter image description here



Programatically What I am expecting:



[

text:
userID: 1
name: 'Mike'
,
children:[

text:
userID: 2
name: 'John'
,
children [

text:
userID: 4
name: 'Hero'
,
children []

]
,

text:
userID: 3
name: 'Kelvin'
,
children []


]

]


Code in Node JS:



let UserProfile = require('./UserProfile');

// Love Dad 83273010
let userID = 51405009;
var allDistributors = Array();
rootUser = new Object();
rootUser.text = userID:userID,name:'Root';
rootUser.children = [];
function getUserTree(userID)
return new Promise( (resolve,reject) =>
/*
* UserDownline Return User child Array
* Format:
* [
* text:
* userID: 45
* name: 'Mike'
* ,
* children:[]
*
* ]
*
*/
UserProfile.getUserChildren(userID).then(async (data) =>
if(data.length > 0)
rootUser.children = data;
/*
* Iterating each user to fetch and assign its child
*/
await rootUser.children.forEach(async (user,index,usrArr) =>

user.children = 'sample'

await getUserTree(user.text.title).then( async(usrChild) =>
/*
Assigning child to root user
*/
usrArr[index].children = usrChild; // STILL NOT ABLE TO ASSIGN VALUE and return user.children as 'sample'
).then(resolve(rootUser));



);
//resolve(rootUser)
//console.log(rootUser)
//return Promise.all(rootUser);
else
resolve([]); // return empty child when no child exist
);
//return rootUser.children;

//console.log(rootUser);
);



//console.log(JSON.stringify(rootUser));
getUserTree(userID).then((data) =>
console.log(JSON.stringify(data));
);









share|improve this question













marked as duplicate by Bergi es6-promise
Users with the  es6-promise badge can single-handedly close es6-promise questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 9 at 12:45


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


















  • await xxx.forEach(async - this does not do what you think it does ... since forEach returns (immediately) undefined, nothing inside the forEach callback is awaited on

    – Jaromanda X
    Mar 9 at 7:53











  • Any idea how can I achieve it or any other way to iterate, so assignment is performed upon completion of getUserTree ?

    – Ashish Patel
    Mar 9 at 10:31











  • Array.map with promise.all

    – Jaromanda X
    Mar 9 at 10:46













1












1








1









This question already has an answer here:



  • Using async/await with a forEach loop

    13 answers



I am trying to build a tree structure by traversing a given ID and attaching its child to the tree. It always assigns user.children = 'sample' instead of fetched user children from user.children = usrChild, also tried usrArr[index].children = 'sample'



What I am trying to implement:
using a userID, I will fetch its children, now for each children i will fetch their children until there are no children left.



function UserProfile.getUserChildren returns a promise with data consisting of all the children.
Now, we iterate each children and fetch their children



Output Expected Visually:



enter image description here



Programatically What I am expecting:



[

text:
userID: 1
name: 'Mike'
,
children:[

text:
userID: 2
name: 'John'
,
children [

text:
userID: 4
name: 'Hero'
,
children []

]
,

text:
userID: 3
name: 'Kelvin'
,
children []


]

]


Code in Node JS:



let UserProfile = require('./UserProfile');

// Love Dad 83273010
let userID = 51405009;
var allDistributors = Array();
rootUser = new Object();
rootUser.text = userID:userID,name:'Root';
rootUser.children = [];
function getUserTree(userID)
return new Promise( (resolve,reject) =>
/*
* UserDownline Return User child Array
* Format:
* [
* text:
* userID: 45
* name: 'Mike'
* ,
* children:[]
*
* ]
*
*/
UserProfile.getUserChildren(userID).then(async (data) =>
if(data.length > 0)
rootUser.children = data;
/*
* Iterating each user to fetch and assign its child
*/
await rootUser.children.forEach(async (user,index,usrArr) =>

user.children = 'sample'

await getUserTree(user.text.title).then( async(usrChild) =>
/*
Assigning child to root user
*/
usrArr[index].children = usrChild; // STILL NOT ABLE TO ASSIGN VALUE and return user.children as 'sample'
).then(resolve(rootUser));



);
//resolve(rootUser)
//console.log(rootUser)
//return Promise.all(rootUser);
else
resolve([]); // return empty child when no child exist
);
//return rootUser.children;

//console.log(rootUser);
);



//console.log(JSON.stringify(rootUser));
getUserTree(userID).then((data) =>
console.log(JSON.stringify(data));
);









share|improve this question















This question already has an answer here:



  • Using async/await with a forEach loop

    13 answers



I am trying to build a tree structure by traversing a given ID and attaching its child to the tree. It always assigns user.children = 'sample' instead of fetched user children from user.children = usrChild, also tried usrArr[index].children = 'sample'



What I am trying to implement:
using a userID, I will fetch its children, now for each children i will fetch their children until there are no children left.



function UserProfile.getUserChildren returns a promise with data consisting of all the children.
Now, we iterate each children and fetch their children



Output Expected Visually:



enter image description here



Programatically What I am expecting:



[

text:
userID: 1
name: 'Mike'
,
children:[

text:
userID: 2
name: 'John'
,
children [

text:
userID: 4
name: 'Hero'
,
children []

]
,

text:
userID: 3
name: 'Kelvin'
,
children []


]

]


Code in Node JS:



let UserProfile = require('./UserProfile');

// Love Dad 83273010
let userID = 51405009;
var allDistributors = Array();
rootUser = new Object();
rootUser.text = userID:userID,name:'Root';
rootUser.children = [];
function getUserTree(userID)
return new Promise( (resolve,reject) =>
/*
* UserDownline Return User child Array
* Format:
* [
* text:
* userID: 45
* name: 'Mike'
* ,
* children:[]
*
* ]
*
*/
UserProfile.getUserChildren(userID).then(async (data) =>
if(data.length > 0)
rootUser.children = data;
/*
* Iterating each user to fetch and assign its child
*/
await rootUser.children.forEach(async (user,index,usrArr) =>

user.children = 'sample'

await getUserTree(user.text.title).then( async(usrChild) =>
/*
Assigning child to root user
*/
usrArr[index].children = usrChild; // STILL NOT ABLE TO ASSIGN VALUE and return user.children as 'sample'
).then(resolve(rootUser));



);
//resolve(rootUser)
//console.log(rootUser)
//return Promise.all(rootUser);
else
resolve([]); // return empty child when no child exist
);
//return rootUser.children;

//console.log(rootUser);
);



//console.log(JSON.stringify(rootUser));
getUserTree(userID).then((data) =>
console.log(JSON.stringify(data));
);




This question already has an answer here:



  • Using async/await with a forEach loop

    13 answers







javascript node.js promise es6-promise






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 9 at 7:19









Ashish PatelAshish Patel

3681311




3681311




marked as duplicate by Bergi es6-promise
Users with the  es6-promise badge can single-handedly close es6-promise questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 9 at 12:45


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Bergi es6-promise
Users with the  es6-promise badge can single-handedly close es6-promise questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 9 at 12:45


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • await xxx.forEach(async - this does not do what you think it does ... since forEach returns (immediately) undefined, nothing inside the forEach callback is awaited on

    – Jaromanda X
    Mar 9 at 7:53











  • Any idea how can I achieve it or any other way to iterate, so assignment is performed upon completion of getUserTree ?

    – Ashish Patel
    Mar 9 at 10:31











  • Array.map with promise.all

    – Jaromanda X
    Mar 9 at 10:46

















  • await xxx.forEach(async - this does not do what you think it does ... since forEach returns (immediately) undefined, nothing inside the forEach callback is awaited on

    – Jaromanda X
    Mar 9 at 7:53











  • Any idea how can I achieve it or any other way to iterate, so assignment is performed upon completion of getUserTree ?

    – Ashish Patel
    Mar 9 at 10:31











  • Array.map with promise.all

    – Jaromanda X
    Mar 9 at 10:46
















await xxx.forEach(async - this does not do what you think it does ... since forEach returns (immediately) undefined, nothing inside the forEach callback is awaited on

– Jaromanda X
Mar 9 at 7:53





await xxx.forEach(async - this does not do what you think it does ... since forEach returns (immediately) undefined, nothing inside the forEach callback is awaited on

– Jaromanda X
Mar 9 at 7:53













Any idea how can I achieve it or any other way to iterate, so assignment is performed upon completion of getUserTree ?

– Ashish Patel
Mar 9 at 10:31





Any idea how can I achieve it or any other way to iterate, so assignment is performed upon completion of getUserTree ?

– Ashish Patel
Mar 9 at 10:31













Array.map with promise.all

– Jaromanda X
Mar 9 at 10:46





Array.map with promise.all

– Jaromanda X
Mar 9 at 10:46












1 Answer
1






active

oldest

votes


















0














As Jaromanda X pointed out, rootUser.children.foreach returns undefined instead of a promise. Consider using rootUser.children.map instead. That returns an array of Promises that you can await on using Promise.all, which returns a promise of an array. Since map does not modify the original array, you would need to assign rootUser.children to the awaited result of Promise.all






share|improve this answer























  • Still same issue, as foreach

    – Ashish Patel
    Mar 9 at 12:56











  • Your example expected result doesn't show a user.text.title property. This results in the id passed to the getUserTree function to be undefined. You would also need to return the result of getUserTree in the map

    – jro
    Mar 9 at 13:14


















1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














As Jaromanda X pointed out, rootUser.children.foreach returns undefined instead of a promise. Consider using rootUser.children.map instead. That returns an array of Promises that you can await on using Promise.all, which returns a promise of an array. Since map does not modify the original array, you would need to assign rootUser.children to the awaited result of Promise.all






share|improve this answer























  • Still same issue, as foreach

    – Ashish Patel
    Mar 9 at 12:56











  • Your example expected result doesn't show a user.text.title property. This results in the id passed to the getUserTree function to be undefined. You would also need to return the result of getUserTree in the map

    – jro
    Mar 9 at 13:14
















0














As Jaromanda X pointed out, rootUser.children.foreach returns undefined instead of a promise. Consider using rootUser.children.map instead. That returns an array of Promises that you can await on using Promise.all, which returns a promise of an array. Since map does not modify the original array, you would need to assign rootUser.children to the awaited result of Promise.all






share|improve this answer























  • Still same issue, as foreach

    – Ashish Patel
    Mar 9 at 12:56











  • Your example expected result doesn't show a user.text.title property. This results in the id passed to the getUserTree function to be undefined. You would also need to return the result of getUserTree in the map

    – jro
    Mar 9 at 13:14














0












0








0







As Jaromanda X pointed out, rootUser.children.foreach returns undefined instead of a promise. Consider using rootUser.children.map instead. That returns an array of Promises that you can await on using Promise.all, which returns a promise of an array. Since map does not modify the original array, you would need to assign rootUser.children to the awaited result of Promise.all






share|improve this answer













As Jaromanda X pointed out, rootUser.children.foreach returns undefined instead of a promise. Consider using rootUser.children.map instead. That returns an array of Promises that you can await on using Promise.all, which returns a promise of an array. Since map does not modify the original array, you would need to assign rootUser.children to the awaited result of Promise.all







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 9 at 10:52









jrojro

615316




615316












  • Still same issue, as foreach

    – Ashish Patel
    Mar 9 at 12:56











  • Your example expected result doesn't show a user.text.title property. This results in the id passed to the getUserTree function to be undefined. You would also need to return the result of getUserTree in the map

    – jro
    Mar 9 at 13:14


















  • Still same issue, as foreach

    – Ashish Patel
    Mar 9 at 12:56











  • Your example expected result doesn't show a user.text.title property. This results in the id passed to the getUserTree function to be undefined. You would also need to return the result of getUserTree in the map

    – jro
    Mar 9 at 13:14

















Still same issue, as foreach

– Ashish Patel
Mar 9 at 12:56





Still same issue, as foreach

– Ashish Patel
Mar 9 at 12:56













Your example expected result doesn't show a user.text.title property. This results in the id passed to the getUserTree function to be undefined. You would also need to return the result of getUserTree in the map

– jro
Mar 9 at 13:14






Your example expected result doesn't show a user.text.title property. This results in the id passed to the getUserTree function to be undefined. You would also need to return the result of getUserTree in the map

– jro
Mar 9 at 13:14






Popular posts from this blog

Google colab Transport endpoint is not connectedHow do I connect to a MySQL Database in Python?Google Colab is very slow compared to my PCGoogle Colab script throws “Transport endpoint is not connected”Presentation mode for Google Colab notebooksGoogle Colab: cell has not been executed in this session?Google Colab and tensorflow: How to hypertune and save a modelIs it possible to connect jupyter running on my laptop with google colabDisplaying all output with linebreaks in Google ColabUsing extensions in Google colabGoogle Colab Error: Buffered data was truncated after reaching the output size limit

IntelliJ IDEA underlines variables when using += in JAVA2019 Community Moderator ElectionHow can I permanently enable line numbers in IntelliJ?Is Java “pass-by-reference” or “pass-by-value”?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?What is the scope of variables in JavaScript?How to determine if variable is 'undefined' or 'null'?How do I convert a String to an int in Java?IntelliJ inspection gives “Cannot resolve symbol” but still compiles codeCreating a memory leak with JavaHow to see JavaDoc in IntelliJ IDEA?

Лубенський полк