I can use access token only inside login function.
here my problem is I need access token for publishing data in other functions like particle.publishEvent, but I am not able use access token because I received it as pending.
That is expected. All of the Particle API functions are asynchronous and return a promise. The first block of code in the then is executed after the token is received, that’s the Login successful message.
The line of code after the then is executed before the operation completes, so it’s undefined at that point. If the code is structured a little differently, it might be a promise instead of undefined, but it won’t be available yet, in any case.
You either need to put all of the code you want to execute in the first part of the then, or use Javascript await so the login function executes synchronously so the next line of code is only executed after the login completes.
I tried below code, I am not able to use access token outside of function, token is undefined. Is this anything have to deal with scope of variable? I am new to javascript. How to use access token outside function? Please give me some example.
var Particle = require('particle-api-js');
var particle = new Particle();
var token;
particle.login({username: username, password: password}).then(
function(data){
console.log('API call completed on promise resolve: ', data.body.access_token);
token = data.body.access_token;
console.log('token: ', token);
},
function(err) {
console.log('API call completed on promise fail: ', err);
}
);
console.log('token: ', token);
O/P:
token: undefined
API call completed on promise resolve: ad4d78b5e7c41xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
token: ad4d78b5e7c41xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
You can try this to list your devices. You can pass token from function to another function in the same way and in this case you don’t need to decelerate var token globally.
var Particle = require(‘particle-api-js’);
var particle = new Particle();
function getListDev(T){
var devicesPr = particle.listDevices({ auth: T});
devicesPr.then(
function(devices){
console.log('All_stuff: ', devices);
console.log('devices', devices.body);
},
function(err){
console.log('List devices call failed: ', err);
console.log('json error', err.body.error);
});
}
particle.login({username: username, password: password}).then(
function(data){
console.log('API call completed on promise resolve: ', data.statusCode);
console.log('token: ', data.body.access_token);
getListDev(data.body.access_token);
},
function(err) {
console.log('API call completed on promise fail: ', err);
}
);
Hey, it cost me some time to understand what Javascript is doing with those .then, async calls and such.
Can I suggest you read this? It's going to help you big time: