I have run into this problem and I am out of ideas.
So in my project, the idea is that the device can register itself in my system.
The device need to send the get request, and in return the access key is send back to the device.
But I have problem to get the access key because of the asynchronous nature of the request.
My code is:
var accessKey;
function registerDevice() {
var options = {
host: this.server_address, // host name
port: 8080, // (optional) port, defaults to 80
path: '/sensor/register', // path sent to server
method: 'GET',
headers: {
'Accept' : 'application/json',
'Content-Type' : 'application/json', }
};
var resData = "";
this.http.request(options, function (res) {
res.on('data', function (data) {
resData += data;
});
res.on('close', function() {
resData = JSON.parse(resData);
});
}).end();
return setTimeout(function () {
resData.access_key;
console.log('timeout', resData.access_key);
return resData.access_key;
},10000);
}
accessKey = registerDevice();
console.log(accessKey);
And after running it I always get the undefined object.
I need the access key for later use, to add it to the header in other requests, but I have no idea for now, how to return it from the registerDevice(). Also the console.log() with 'timeout' is returning the valid access key.
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
Hi everyone!
I have run into this problem and I am out of ideas.
So in my project, the idea is that the device can register itself in my system.
The device need to send the get request, and in return the access key is send back to the device.
But I have problem to get the access key because of the asynchronous nature of the request.
My code is:
And after running it I always get the undefined object.
I need the access key for later use, to add it to the header in other requests, but I have no idea for now, how to return it from the registerDevice(). Also the console.log() with 'timeout' is returning the valid access key.
Any help will be mostly appreciated.