Wrapping Auth0's parseHash function in a Promise

南笙酒味 提交于 2019-12-10 21:37:03

问题


auth0.js has a function that's used to parse the URL hash fragment and extract the authentication result therefrom. I'm wrapping this function within one called loadSession as follows:

public loadSession(): void {
  this.auth0.parseHash((err, authResult) => {
    if (authResult) {
      window.location.hash = '';
      localStorage.setItem('token', authResult.accessToken);
      // TODO (1)
    } else if (err) {
      // TODO (2)
    }
  });
}

As seen above, parseHash takes a callback function as an argument and I cannot control that. I would like loadSession to return a Promise that would be resolved at // TODO (1) and rejected at // TODO (2) above. This way I can do obj.loadSession().then(() => { // do something if successful }).catch((err) => { // raise error if not })


回答1:


Simply wrap it inside a promise:

public loadSession() {
    return new Promise((resolve, reject) => {
        this.auth0.parseHash((err, authResult) => {
            if(authResult) {
                window.location.hash = '';
                localStorage.setItem('token', authResult.accessToken);
                resolve(authResult);
            } else if (err) {
                reject(err);
            }
        });
    });
}



回答2:


You can pretty much pass any callback function to a function that returns a promise given:

  1. The callback is the last argument
  2. The callback function takes error as it's first argument

Here is an example:

const asPromise = 
  (context)   =>
  (fn)   =>
  (args)      =>
    new Promise(
      (resolve,reject) =>
        fn.apply(
          context,
          (args||[]).concat(
            function(){
              if(arguments[0]){
                reject(arguments[0]);return;
              }
              resolve(Array.from(arguments).slice(1));
            }
          )
        )
    );

// to apply parseHash on auth0
public loadSession(): Promise {
  return asPromise(this.auth0)(this.auth0.parseHash)()
  .then(
    ([authResult])=>{
      if (authResult) {
        window.location.hash = '';
        localStorage.setItem('token', authResult.accessToken);
        //whatever you return here is the resolve
        return authResult;
      } 
      //just throw in a promise handler will return a rejected promise
      // this is only for native promises, some libraries don't behave
      // according to spec so you should test your promise polyfil if supporting IE
      throw "Promise resolved but got no authResult";
    }
  )
}



回答3:


public loadSession(): Promise {
  return new Promise((resolve, reject) => {
    this.auth0.parseHash((err, authResult) => {
    if (authResult) {
      window.location.hash = '';
      localStorage.setItem('token', authResult.accessToken);
      // TODO (1)
      // resolve(something)
    } else if (err) {
      // TODO (2)
      // reject(something)
    }
  });
}

For more information about using Promise API, you can visit MDN Docs




回答4:


Or you can use a tiny library that does that for you: promisify-auth0 on GitHub, promisify-auth0 on npmjs.org.

Now updated to version 9.5.1.



来源:https://stackoverflow.com/questions/47620540/wrapping-auth0s-parsehash-function-in-a-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!