Home > Enterprise >  Return value is null when return value is placed inside the .then function?
Return value is null when return value is placed inside the .then function?

Time:06-27

I've been trying to fix the following issue for the past two days. I want to create a user and after that return a list as shown below:

exports.createUser = functions.https.onCall((data,context) => {
  try {
    admin.auth().createUser({
      email: "[email protected]"
      password: "a3tbmz"
    }).then((arg) => {
    // a) if I return a variable here it doesn't work
    });
    // b) if I return a variable here it works
  }
});

Returning a variable using method b) it works but I need to return the variable using method a). I can't use async and await because I will receive the following error:

 error  Parsing error: Unexpected token =>

✖ 1 problem (1 error, 0 warnings)

I appreciate it if someone can help me with this, I spent the entire weekend trying to solve this...

CodePudding user response:

You need to return a value from the top-level code of your function, otherwise Cloud Functions may/will terminate your code before the asynchronous operation has completed.

exports.createUser = functions.https.onCall((data,context) => {
  try {
    return admin.auth().createUser({
      email: "[email protected]"
      password: "a3tbmz"
    }).then((arg) => {
      return "result";
    }).catch((err) => {
      return err;
    });
  }
});

Also see the second code snippet in the documentation on sending back the result, which does something similar.

CodePudding user response:

try

let userCreated = false

exports.createUser = functions.https.onCall((data,context) => {
  try {
      admin.auth().createUser({
      email: "[email protected]"
      password: "a3tbmz"
    })
userCreated = true

if(userCreated){
  return // the object you wanted to return
}

  } catch(err){
     throw new Error(err)
}
});
  • Related