I’m trying to implement an login mechanize and not able to return a value from the callback function. I’m using this npm package: auth0-js. There’s two files in my setup. The first one is authService.js where I have my login logic:
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, };
The second one: index.js
import { handleLogin, initializeAuth0Client } from "authService"; const auth0Client = initializeAuth0Client(domain, redirectUri, clientID); const authResponse = handleLogin(auth0Client, user); console.log(authResponse) // undefined
I tried returning the value from the callback, as well as assigning the result to a local variable inside the function and returning that one, but none of those ways actually return the response. I saw this answer, but it didn’t help much.
Advertisement
Answer
In the following snippet, both lines will always try to run at the same time.
const authResponse = handleLogin(auth0Client, user); console.log(authResponse) // undefined
console.log(authResponse)
is not going to wait for handleLogin
to finish and return authResult
authResult
is only available inside of the callback
function handleLogin(client, user) { return client.login( { realm, username, password, }, (err, authResult) => { if (authResult) { console.log(authResponse) // works! return authResult; } } ); }
If you want your code synchronously, or have handleLogin(auth0Client, user);
resolve before having the rest of the code run, you can turn handleLogin
into a function that returns a Promise that resolves with the authResponse
. This will cause console.log(authResponse)
to wait for 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!
If you are doing this in Node, you have to make sure that you call this in an async
function. Placing it inside a wrapper function should suffice
async function auth() { const auth0Client = initializeAuth0Client(domain, redirectUri, clientID); const authResponse = handleLogin(auth0Client, user); console.log(authResponse) // works! } auth()