Javascript 无法从auth0 js返回authResponse
我试图实现登录机械化,但无法从回调函数返回值。我正在使用此npm包:。我的设置中有两个文件。 第一个是authService.js,其中我有我的登录逻辑:Javascript 无法从auth0 js返回authResponse,javascript,asynchronous,callback,auth0,Javascript,Asynchronous,Callback,Auth0,我试图实现登录机械化,但无法从回调函数返回值。我正在使用此npm包:。我的设置中有两个文件。 第一个是authService.js,其中我有我的登录逻辑: import auth0 from "auth0-js"; function initializeAuth0Client(domain, redirectUri, clientID) { return new auth0.WebAuth({ domain: "{YOUR_AUTH0_DOMAIN}&
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
我尝试从回调中返回值,并将结果赋给函数中的局部变量并返回该变量,但这些方法都没有实际返回响应。我看到了,但没有多大帮助。在下面的代码段中,两行将始终尝试同时运行
const authResponse=handleLogin(auth0客户端,用户);
console.log(authResponse)//未定义
console.log(authResponse)
不会等待handleLogin
完成并返回authResult
authResult
仅在回调内部可用
函数handleLogin(客户端、用户){
返回client.login(
{
王国,
用户名,
密码,
},
(错误,authResult)=>{
如果(authResult){
console.log(authResponse)//工作正常!
返回结果;
}
}
);
}
如果您希望代码同步,或者具有handleLogin(auth0Client,user)代码>解析在运行其余代码之前,可以将handleLogin
转换为一个函数,该函数返回一个承诺,该承诺通过authResponse
解析。这将导致console.log(authResponse)
等待handleLogin(auth0客户端,用户)代码>
函数handleLogin(客户端、用户){
返回新承诺((解决、拒绝)=>{
client.login(
{
王国,
用户名,
密码,
},
(错误,authResult)=>{
如果(authResult){
解决(结果);
}
}
}
);
}
const auth0Client=initializeAuth0Client(域、重定向URI、客户端ID);
const authResponse=wait handleLogin(auth0客户端,用户);
console.log(authResponse)//工作正常!
如果要在节点中执行此操作,则必须确保在async
函数中调用此函数。将其放置在包装函数中就足够了
异步函数auth(){
const auth0Client=initializeAuth0Client(域、重定向URI、客户端ID);
const authResponse=handleLogin(auth0客户端,用户);
console.log(authResponse)//工作正常!
}
auth()