Skip to content
Advertisement

Get a value from a callback in another function NodeJS

I’m desperately trying to recover the value of a callback function but I have no idea how to do that. I have a function where I execute this code:

if (final.error !== undefined) {
                console.log("Initial authentication:", final.error_description, "Please refresh the authentication grant");
                extAuthCallback(84);
            } else {
                tokens.set('access_token', final.access_token)
                    .set('expires_in', final.expires_in)
                    .set('refresh_token', final.refresh_token)
                    .set('refresh_date', moment())
                    .write()
                extAuthCallback(1);
            }
        }); 

Who performs this function:

function extAuthCallback(result) {
    return result;
}

And which is called by this variable:

let authentication = auth.extAuth(access_token, auth.extAuthCallback);

I would like my `authentication’ variable to take the value returned in the callback, and I have no idea how to do that. Returning the callback function to my original function doesn’t work.

Advertisement

Answer

You could use a promise, would need to use an async function as well though.

function asyncExtAuth(access_token) {
  return new Promise(resolve => {
    auth.extAuth(access_token, resolve);
  });
}
let authentication = await asyncExtAuth(access_token);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement