1

I am attempting to returning an array that gets populated inside a loop, iterating over entries from a JSON response.

We get a list of nodes from an API endpoint, check if each node is halted or not. If it is halted, we push them to the list.

getHaltedNodes = (nodeId, callback) -> 
  url = "some_api_endpoint/" +nodeIid
  request url, (error, response, body) -> 
    haltedNodes = []
    for node in JSON.parse(body) -> 
      do (node) ->
        checkIfHalted node, (haltedNode) -> 
          haltedNodes.push haltedNode
          #1 console.log haltedNode
    #2 console.log haltedNodes
   return callback haltedNodes


getNodeId nodeName, (nodeId) ->
  getHaltedNodes nodeId, (haltedNodes)->
    robot.send haltedNodes

In the first console.log, I've verified that checkIfHalted() correctly returns the node information if the node is halted. But the second console.log always shows an empty list.

I am aware that this is something to do with asynchronous requests but I'm having trouble to wrap my heard around it and come up with a solution. I am using callbacks so that the function 'waits'. How can i return the list of halted nodes after it's been populated by the loop?

mandopaloooza
  • 149
  • 1
  • 1
  • 10

0 Answers0