0

I'm trying to get the value of the variable

My actual code is:

const curl = require('curl');

var url = "https://login.microsoftonline.com/meuid/oauth2/v2.0/token"
var body = "client_id=meuid&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=meuid&grant_type=client_credentials"
var options = "Content-Type: application/x-www-form-urlencoded"
var x = "";

curl.post(url, body, options, function(err, response, xbody) {
    var x = xbody
})

console.log('result' + x)

What i'm doing wrong? why i cant get the value?

  • You're running console.log before the 'x' affectation. Look at the doc for async in nodejs – BENARD Patrick Jan 22 '20 at 14:46
  • I need console.log outside the function because i will try export my token after @BENARDPatrick – Patrik Roger Jan 22 '20 at 14:47
  • Yep, look at `await / async` in nodejs, it's what you need to understand... – BENARD Patrick Jan 22 '20 at 14:50
  • It's possible to do what i want? after i will try something like "export x", inside the function i get the error "import' and 'export' may only appear at the top level" @BENARDPatrick – Patrik Roger Jan 22 '20 at 14:54
  • Why are U defining variable inside curl function ??? – SkorpEN Jan 22 '20 at 14:57
  • @SkorpEN This is the code from my getToken.js module, i will try export the value of xbody after. If i can console.log it i can export it. – Patrik Roger Jan 22 '20 at 15:02
  • U could use variable delared above. U do not need to declare it inside function. – SkorpEN Jan 22 '20 at 15:06
  • It's a duplicate of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call. Check this it will help you a lot. – Naor Levi Jan 22 '20 at 15:48
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Naor Levi Jan 22 '20 at 15:49

1 Answers1

0

If no async present this will work. When U want to use results from async you could use then on promise or use async function as @BENARD Patrick suggested.

var x = "";

function f(){
 let z="xbody"
 x=z;
}
f();
console.log('result ' + x)
SkorpEN
  • 2,491
  • 1
  • 22
  • 28