-1

I try to use the promise respond from a $http.post, to get back the new ID of the record as integer and use it for the next $http.post. I used How do I return the response from an asynchronous call? for help but it still don´t work.

var streckenId;
var trackpunktId;

var getStreckeID = function () {
  $http.post(dbStrecke, {"ort": location, "distanz": km}).then(function (response) {
    streckenId = response.data;
    console.log("ID (then): " + streckenId); // return ID
  });
  return streckenId;
};

streckenId = getStreckeID();
console.log("StreckeID:" + streckenId); //return undefined

The last console.log still say that "streckenId" is undefined.

Community
  • 1
  • 1
74ck
  • 65
  • 2
  • 9
  • You didn't read the answer to the question very well, you are still trying to use something that hasn't been set yet. – Patrick Evans May 31 '16 at 19:49
  • are you kidding me? I have try to solve with the thread above, but it don´t work, so I still get no help? great community!! – 74ck May 31 '16 at 19:56
  • It does work, you simply implemented it wrong. – Patrick Evans May 31 '16 at 19:57
  • yeah so tell me what did I do wrong? I´ve read the answers and tried different things, but nothing worked, so I ask here for advance... – 74ck May 31 '16 at 20:01

1 Answers1

0

modify you code such this

 var streckenId;
 var trackpunktId;

 var getStreckeID = function () {
    return $http.post(dbStrecke, {"ort": location, "distanz": km});
 };

 getStreckeID().then(function(response) {
    streckenId = response.data;
    console.log("ID (then): " + streckenId); // return ID
 });

Data from server will be available only when promise is resolved . So assignment will be performed after resolving the promise . Otherwise streckenId will be undefined.

Ashot
  • 1,229
  • 1
  • 12
  • 13