skip to Main Content

So basicly i have a function, that’s starts OAuth flow (redirecting to google oauth login page for example):

async function signIn() {
  // start Oauth flow
}

and for instance i want to use it in useEffect like this:

...
useEffect(() => {
  async function someAsyncFunc() {
    randomFunc1();
    await signIn();
    randomFunc2();
  }

  someAsyncFunc();
}, []);
...

in this case randomFunc2() will never occur because signIn() will redirect to another url

So my question is how i can tell for other developers that there’s no point to call other functions after signIn(), because they will never be executed. I heard in typescript there is type called never, but i’m not sure if this gonna work in my case.

Edit: as example redirect function in nextjs navigation returns never

Any sugestions?

2

Answers


  1. Change function name so that it is clear that you will do sign in and redirect.

    Login or Signup to reply.
  2. This should work but doesn’t due to a typescript bug

    async function signIn(): Promise<Never> {
    
    }
    

    But currently this doesn’t create errors as expected due to this TypeScript bug

    Workaround

    There is no real neat solution that works right now, but you can at least prevent the most common mistake (code not running that should be run) by just not returning a promise if it will never complete

    async function _signIn() {
      // start Oauth flow
    }
    
    function signIn(): void {
        _signIn();
    }
    

    signIn now does not return a promise, so it can’t be awaited. This way it is impossible to do something after signIn completes.

    You can still write code in the lines afterwards but they will execute like normal, not wait will the sign in completes.

    In your example:

    // doesn't even need to be async now
    async function someAsyncFunc() {
        randomFunc1();
        signIn();
        randomFunc2();
    }
    

    randomFunc1 and randomFunc2 will both run as intended, regardless or where you place signIn

    Note this only works if randomFunc1 etc. are not async otherwise they may not complete before the pages closes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search