简体   繁体   English

在Promise中包装Auth0的parseHash函数

[英]Wrapping Auth0's parseHash function in a Promise

auth0.js has a function that's used to parse the URL hash fragment and extract the authentication result therefrom. auth0.js有一个用于解析URL哈希片段并从中提取身份验证结果的函数。 I'm wrapping this function within one called loadSession as follows: 我将这个函数包装在一个名为loadSession函数中,如下所示:

 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. 如上所示, parseHash将回调函数作为参数,我无法控制它。 I would like loadSession to return a Promise that would be resolved at // TODO (1) and rejected at // TODO (2) above. 我想loadSession返回一个Promise ,它将在// TODO (1)处解析,并在// TODO (2)处拒绝。 This way I can do obj.loadSession().then(() => { // do something if successful }).catch((err) => { // raise error if not }) 这样我就可以做obj.loadSession().then(() => { // do something if successful }).catch((err) => { // raise error if not })

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);
            }
        });
    });
}

You can pretty much pass any callback function to a function that returns a promise given: 您几乎可以将任何回调函数传递给返回给定的promise的函数:

  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";
    }
  )
}
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 有关使用Promise API的更多信息,您可以访问MDN Docs

Or you can use a tiny library that does that for you: promisify-auth0 on GitHub, promisify-auth0 on npmjs.org. 或者你也可以使用这是否对你一个小小的图书馆: promisify-auth0在GitHub上, promisify-auth0上npmjs.org。

Now updated to version 9.5.1 . 现在更新到9.5.1版。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将promise包装为Sync功能 - Wrapping promise into a Sync function 用带有aych的aych循环包装函数 - Wrapping a function with an aych loop with a promise Typescript异步函数包装Promise - Typescript async function wrapping promise PassportJS和Auth0之间是什么关系? - What's the relationship between PassportJS & Auth0? Auth0 Lock中未触发认证回调函数 - The authentication callback function is not triggered in Auth0 Lock 我在Auth0的节点程序包中,特别是在他们的AuthenticationClient和ManagementClient API中收到无法识别的函数错误 - I'm getting an error for an unrecognized function within Auth0's node package, specifically in their AuthenticationClient and ManagementClient API Lambda function 未通过 Auth0 node-auth0 SDK 调用 auth0 方法 - Lambda function not calling auth0 methods via Auth0 node-auth0 SDK 将函数包装在promise中是否会导致该函数的代码被另一个线程并行执行? - Does wrapping a function in a promise cause the function's code to be executed in parallel by another thread? 包装回调函数时承诺作为函数返回 - Promise returning as a function when wrapping callback function 在Promise中包装使XMLHttpRequest的绑定函数时出现问题 - Problem wrapping a binded function that makes an XMLHttpRequest in a Promise
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM