[Solved] Why does the code execute without waiting for await to return in dart/flutter?


Taking a closer look at your Firebase function, I was able to identify two issues:

  1. Usage of both await and then keywords in the same function. These two statements do the same thing. Quoting this accepted answer.

await is just an internal version of .then() (doing basically the same thing). The reason to choose one over the other has to do with desired coding style or coding convenience. Certainly, the interpreter has a few more opportunities to optimize things
internally with await, but it’s unlikely that should be how you decide which to use.

In other words, it is an overhead to use both of them.

  1. The next piece of code returns results only in the context of the then nested Promise which is not the same context of the Cloud Function Register. In other words, you receive a null value in flutter because the Cloud Function is not returning anything in its running context.
.then(() => {
        console.log("done")
        return "done"
      })
.catch((error: any) => {
        console.error(error.code);
        return error.code

As I mentioned earlier, then and await are used for the same purpose, so you have two options to correct the code.

You can use await:

exports.Register = functions.https.onCall(async (data, context) => {
[...]
 try {
      await admin.auth()
        .createUser({
            email: email,
            emailVerified: false,
            password: pass,
            displayName: Name,
            disabled: false,
        });
        return "user successfully registered";

      
    } catch (error) {
      console.log(error);
      return "the function failed;check Cloud Logging for the reason";
    }
}

Or you can use then:

exports.RegisterThen = functions.https.onCall((data, context) => {
[...]
return admin.auth()
      .createUser({
            email: email,
            emailVerified: false,
            password: pass,
            displayName: Name,
            disabled: false,
        })
          .then(() => {return  "user successfully registered"})
          .catch(error => {
            console.log(error);
            return "the function failed;check Cloud Logging for the reason";
          });
}

Please notice how the function is defined with async when I use await and how async is not used if I am using the then function from Promises.

I hope you find this useful

1

solved Why does the code execute without waiting for await to return in dart/flutter?