I have used the following code sample to call a API which returns a access token.
var responsedata = '';
unirest.post('')
.headers({'Content-Type': 'application/x-www-form-urlencoded'})
.send('apiKey=xewsdw232')
.send('username=theuser')
.end(function (response) {
console.log(response.body);
responsedata = response.body;
});
console.log(responsedata);
I have used the following code sample to call a API which returns a access token.
var responsedata = '';
unirest.post('http://sandbox./api/getToken')
.headers({'Content-Type': 'application/x-www-form-urlencoded'})
.send('apiKey=xewsdw232')
.send('username=theuser')
.end(function (response) {
console.log(response.body);
responsedata = response.body;
});
console.log(responsedata);
Response
{ data: { token: 'JhbGciOiJIUzI1NiJ9',transID:'00582',errorCode: '00',errorMessage: '' } }
I do get response which gets logged into the console but unable to assign it to a variable to that I can work with it outside the call function. I am struggling with understanding how callbacks work in javascript.
Share Improve this question edited Dec 25, 2018 at 18:04 Ahmed Reza asked Dec 24, 2018 at 15:13 Ahmed RezaAhmed Reza 231 silver badge4 bronze badges 9- Please show us the response you get. – Matthijs Commented Dec 24, 2018 at 15:22
- Question edit included the response log – Ahmed Reza Commented Dec 25, 2018 at 18:06
- you should understand how Javascript work first. JS working asynchronous. you are trying to get value before its assigned. – Nazır Dogan Commented Dec 25, 2018 at 18:08
-
I think in your code you would use
responsedata.data
. Can you post the code where you are trying to use the data, with an explanation of what isn't working? – Toby Commented Dec 25, 2018 at 18:08 - The last line console.log(responsedata) logs empty string. So I guess the variable responsedata isn't getting response.body value – Ahmed Reza Commented Dec 25, 2018 at 18:11
2 Answers
Reset to default 3HTTP requests are asynchronous in nature. You do not get the response instantly which means javascript doesn't wait for the response instead execution is continued and whenever a response is returned, the callback gets called.
If you want to return this response, encapsulate this code in the function and return a resolved promise.
function getToken() {
return new Promise((resolve, reject) => {
unirest.post('http://sandbox./api/getToken')
.headers({
'Content-Type': 'application/x-www-form-urlencoded'
})
.send('apiKey=xewsdw232')
.send('username=theuser')
.end(function (response) {
if (response.error) {
return reject(response.error)
}
return resolve(response.body);
});
})
}
getToken().then((body) => console.log("success", body)).catch((error) =>
console.log("error", error))
JS working asynchronous. you are trying to get value before its assigned.check this example. you are making request. it takes time but your program will not stop. so you cannot get value outside of function https://repl.it/repls/OutgoingFreshOutput