Functions and return data (beginner)

Hello.

I have a function written on the server side.

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;
  },
  function(err) {
    console.log('API call completed on promise fail: ', err);
  }
);

This function works fine.
now I need to be able to access the data stored in “token” in my other function.

var devicesPr = particle.listDevices({ auth: token });

    devicesPr.then(
      function(devices){
        console.log('Devices: ', devices);
      },
      function(err) {
        console.log('List devices call failed: ', err);
      }
);

But i always get that the token is undefined. All this code is written on server side.
Right now im only testing to see what data i get and so on, so im not really doing anything on the client side.

How do i pass my token data to my other function?

BR
Dimi

listDevices is probably running before the login promise resolves and sets token to a value.

If you’re new to promises, read a guide like this one to get a handle on it: https://www.promisejs.org/

To immediately fix it you should move the code from the second textarea into the function called when the promise successfully resolves, which is when you’ll know what the value of token should be. Once you know more about promises you’ll be able to anticipate them and design for their use.

Meteor 1.3 also supports ES7 async/await syntax, which you could consider using for a more expressive way of doing the same thing.

1 Like

aaaa i see :slight_smile:

Thank you very much.
/Dimi