0

I am trying to get the uid value returned successfully by the following function, and use it as a variable outside of the function as a constant or variable. Below is my code. I am new to node js. please help me. thank you in advance

admin.auth().getUserByEmail(email)
  .then(function(userRecord) {
    console.log('Successfully fetched user data:', userRecord.toJSON());
    var userdata = userRecord.toJSON();
    var uid = userdata.uid;
    console.log('uid', uid);
    return uid;
});
JRichardsz
  • 14,356
  • 6
  • 59
  • 94
  • You are on the right track with Promises. If you really need to get the value back to the lower level, you can use [`async/await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). – Seblor Sep 23 '19 at 13:32
  • Your code creates a promise. You use either `.then()` or `await` with that promise to get its resolved value. `return uid` sets the resolved value of the promise. So you use `.then()` or `await` with that promise to get access to that value. – jfriend00 Sep 23 '19 at 14:11

1 Answers1

0

Short answer

No, you can not use uid value outside your function(userRecord) function. This is due to Asynchronously nature of javascript.

There are dirty techniques to make it works, but are dirty

Here some lectures:

Synchronous way (other languages like java, c#, etc)

//this sentence wait until userRecord
var userRecord = getUserByEmail(email);
//userRecord is ready to use as variable in 
//any section of your code
var uid = getUidFromUser(userRecord);
createUserUidInDatabase(uid);

Asynchronous way with callbacks (javascript)

function createUserUidInDatabase(uid){
  //...
}

function getUidFromUser(userRecord){
  var userdata = userRecord.toJSON();
  var uid = userdata.uid;
  return createUserUidInDatabase(uid);
}

function getUserByEmail(email, callback){
  admin.auth().getUserByEmail(email)
    .then(function(userRecord) {      
      return callback(userRecord);
  });
}

getUserByEmail("marty@stackoverflow.com",getUidFromUser);

Asynchronous way with promises (javascript)

https://www.codingame.com/playgrounds/347/javascript-promises-mastering-the-asynchronous/your-first-code-with-promises

JRichardsz
  • 14,356
  • 6
  • 59
  • 94