0

Can anyone please suggest what I am doing wrong here. I want to get same output with both console.log() statements.

createModel(){
  getvalue("asdfgh");
}
var myservice;
function getvalue(value){
  myservice = value; console.log("inside: "+JSON.stringify(myservice));
  //prints: asdfg
}
createModel();
console.log("outside: "+JSON.stringify(myservice));//prints: undefined
return (myservice);
Pointy
  • 405,095
  • 59
  • 585
  • 614
Armghn
  • 144
  • 2
  • 14
  • 2
    Your code as posted works fine. I suspect that your *actual* code does some asynchronous operation in `getvalue()`. – Pointy Dec 28 '16 at 19:26
  • 1
    [See this question for more information.](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Pointy Dec 28 '16 at 19:27
  • thanks for pointing this out. I specified 'async: false' & it worked fine. – Armghn Dec 28 '16 at 20:49
  • Well that's good, but note that `async: false` will generally result in poor user experience; the user's browser freezes up while waiting for the response. Chrome may even pop up a warning message. – Pointy Dec 28 '16 at 21:19
  • so how should it be handled? – Armghn Jan 04 '17 at 14:55
  • Do things *asynchronously* and process results in a callback function. That's the general pattern for coding in JavaScript. – Pointy Jan 04 '17 at 14:56
  • thanks man, I'll make appropriate changes in my code. – Armghn Jan 04 '17 at 16:09

0 Answers0