无法 return 来自 auth0-js 的 authResponse

Not able to return authResponse from auth0-js

我正在尝试实现登录机制,但无法 return 来自回调函数的值。我正在使用这个 npm 包:auth0-js。我的设置中有两个文件。 第一个是 authService.js 我有我的登录逻辑:

import auth0 from "auth0-js";

function initializeAuth0Client(domain, redirectUri, clientID) {
  return new auth0.WebAuth({
    domain: "{YOUR_AUTH0_DOMAIN}",
    clientID: "{YOUR_AUTH0_CLIENT_ID}",
  });
}

function handleLogin(client, user) {
  return client.login(
    {
      realm,
      username,
      password,
    },
    (err, authResult) => {
      if (authResult) {
        return authResult;
      }
    }
  );
}

module.exports = {
  handleLogin,
  initializeAuth0Client,
};

第二个:index.js

import { handleLogin, initializeAuth0Client } from "authService";


const auth0Client = initializeAuth0Client(domain, redirectUri, clientID);
const authResponse = handleLogin(auth0Client, user);
console.log(authResponse) // undefined

我尝试 return 从回调中获取值,并将结果分配给函数内部的局部变量并 return 获取那个值,但是 none实际上 return 响应的方式。我看到了 this answer,但没有太大帮助。

在下面的代码片段中,两行总是同时尝试 运行。

const authResponse = handleLogin(auth0Client, user);
console.log(authResponse) // undefined

console.log(authResponse) 不会等待 handleLogin 完成并且 return authResult

authResult 仅在回调内部可用

function handleLogin(client, user) {
  return client.login(
    {
      realm,
      username,
      password,
    },
    (err, authResult) => {
      if (authResult) {
        console.log(authResponse) // works!
        return authResult;
      }
    }
  );
}

如果您希望您的代码同步,或者在获得其余代码 运行 之前先解析 handleLogin(auth0Client, user);,您可以将 handleLogin 转换为 return 的函数这是一个使用 authResponse 解析的 Promise。这将导致 console.log(authResponse) 等待 handleLogin(auth0Client, user);

function handleLogin(client, user) {
  return new Promise((resolve, reject) => {
    client.login(
      {
        realm,
        username,
        password,
      },
      (err, authResult) => {
        if (authResult) {
          resolve(authResult);
        }
      }
    }
  );
}
const auth0Client = initializeAuth0Client(domain, redirectUri, clientID);
const authResponse = await handleLogin(auth0Client, user);
console.log(authResponse) // works!

如果您在 Node 中执行此操作,则必须确保在 async 函数中调用它。将它放在包装函数中就足够了

async function auth() {
  const auth0Client = initializeAuth0Client(domain, redirectUri, clientID);
  const authResponse = handleLogin(auth0Client, user);
  console.log(authResponse) // works!
}

auth()