Any feedback appreciated on how to resolve / structure logic given async code? Thanks!
Method
const getRelatedNodes = async (root) => {
const n_nodes = []
const links = await getAllLinks()
links.forEach(async link => {
const other_nodes = link.parties.filter(x => x.id != root.id)
other_nodes.forEach(async party => {
const obj = await fetchEntityById(party.id)
console.log("Line 215! Received entity from promise => ", obj)
const node = {
"data": {
"output": obj.info,
}
}
console.log("Line 222! pushing node to list => ", node)
n_nodes.push(node)
})
console.log("Line 225! New node should be added to nodes list => ", n_nodes)
})
console.log("Line 229!!! Logging final output in getNodes =>" , n_nodes)
// return n_nodes
}
Expected Logging: Each node is pushed to the list after a promise returns an object to be modified
Line 222! pushing node to list => { data: { output: 'Foo-tatstic' }}
Line 225! New node should be added to nodes list => [{ data: { output: 'foo' }}]
Line 215! Received entity from promise => { id: 'bar' }
Line 222! pushing node to list => { data: { output: 'Bar-tatstic'} }
Line 225! New node should be added to nodes list => [{ data: { output: 'foo' }}, { data: { output: 'bar'} }]
Line 215! Received entity from promise => { id: 'baz' }
Line 222! pushing node to list => { data: { ouput: 'Baz-tatstic'} }
Line 225! New node should be added to nodes list => [{ data: { output: 'Foo-tatstic' }}, { data: { output: 'Bar-tatstic'} }, { data: { ouput: 'Baz-tatstic'} }]
Line 229!!! Logging final output in getNodes => [{ data: { output: 'Foo-tatstic' }}, { data: { output: 'Bar-tatstic'} }, { data: { ouput: 'Baz-tatstic'} }]
Actual Logging: Nodes not getting added to list until after the list is returned
Line 225! New node should be added to nodes list => []
Line 225! New node should be added to nodes list => []
Line 229!!! Logging final output in getNodes => []
Line 215! Received entity from promise => { id: 'foo', }
Line 222! pushing node to list => { data: { output: 'Foo-tatstic' }}
Line 215! Received entity from promise => { id: 'bar' }
Line 222! pushing node to list => { data: { output: 'Bar-tatstic'} }
Line 215! Received entity from promise => { id: 'baz' }
Line 222! pushing node to list => { data: { output: 'Baz-tatstic'} }