0

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. My first code:

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, so can anybody tell me what I do wrong? I hope anybody can help me

74ck
  • 55
  • 1
  • 8
  • 2
    Take a look at http://stackoverflow.com/q/14220321/616717. It seems you do not fully understand an asynchronous flow. – Zhegan May 31 '16 at 17:53
  • 1
    Right, because you're still trying to get the value of your variable before the service has responded. Put the `console.log` in the `then()` function. – Heretic Monkey May 31 '16 at 17:55
  • Try logging response.data first before assigning it to streckenId in first block of code , so that you can get some idea whats the http call is returning – Pandiyan Cool May 31 '16 at 17:57
  • It´s not a problem with the server, because if I use an api online tool, the server respond with the IDs. – 74ck May 31 '16 at 18:00
  • @Pandiyan Cool: If I put the console.log into the then block, it respond with the id which I needed, but I also need to assign the value to use it outside the then block – 74ck May 31 '16 at 18:02
  • `$http` is async. You need to wait for the server to finish before proceeding to get the id's. You need to do this: `$http.post(step1).then(step2).catch(step1error);` – Kyle May 31 '16 at 18:03

0 Answers0