0

I am using nodejs for creating REST apis and wanted to store resolved data from multiple promises in to single variable.

Sample code :

var resultset={};

function getAllTeams()
{
     return M.savelatlong(data)
          .then(function(result){  return M.getTeam(id); })
          .then(function(teams){  return teams;})
          .catch(function(error){res.json({status:'success',type:false,msg:error.code});});
}



getAllTeams().then(function(result){
    console.log(result);  // This prints data
    resultset.data=result;
});

console.log(resultset); // Always empty
res.json({status:'success',type:true,data:resultset});

But my resultset variable is always empty.Am I am doing it in a right way or is there any other way to do it.

I tried one solution that is sending response with then statement which works so does that mean I have to always send response within then statements

getAllTeams().then(function(result){
    res.json({status:'success',type:true,data:result});
});
Vibhas
  • 241
  • 5
  • 20

1 Answers1

0

You need to put this

console.log(resultset); // Always empty res.json({status:'success',type:true,data:resultset});

inside

getAllTeams().then(function(result){ console.log(result); // This prints data resultset.data=result; });

Your response are being sent before promise resolves. That's the issue.

Hope this helps.

Mykola Borysyuk
  • 3,373
  • 1
  • 18
  • 24