0

I wrote a promise function in a firebase.js to return access key which I wanted to use everywhere after I start the server. But for some reason when I export the module and use it in app.js, I can't print the returned access_token Or a better question would be , how to use the access_token everywhere globally after the server is started.

Firebase.js is below

var {google} = require('googleapis');
var MESSAGING_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
var SCOPES = [MESSAGING_SCOPE];
var http = require('http');

function getAccessToken() {
    return new Promise(function(resolve, reject) {
        var key = require('./serviceAccountKey.json');
        var jwtClient = new google.auth.JWT(
            key.client_email,
            null,
            key.private_key,
            SCOPES,
            null
        );
        jwtClient.authorize(function(err, tokens) {
            if (err) {
                reject(err);
                return;
            }
            resolve(tokens.access_token);
        });
   });
}

getAccessToken().then(function(access_token){

    //console.log(access_token);
    return access_token;
})

module.exports.getAccessToken = getAccessToken

Below is app.js

const express = require("express");
const ac = require('./firebase.js');
const app = express();

console.log(ac.getAccessToken);

const port = process.env.PORT || 1111 ;

app.listen(port, () => {
  //console.log(`server up and running on ${process.env.PORT}`);
  console.log(`server up and running on ` + port);
});

I start the server by nodemon index.js

aasir khan
  • 37
  • 5
  • https://stackoverflow.com/q/14220321/438992 – Dave Newton Jul 02 '22 at 21:54
  • I'd recommend exporting the promise rather than the function so `module.exports.getAccessToken = getAccessToken` would change to `module.exports.accessTokenPromise = getAccessToken();` and `console.log(ac.getAccessToken);` would change to `ac.accessTokenPromise.then(token => console.log(token));`. – Rocky Sims Jul 02 '22 at 22:09
  • In `app.js`, `ac.getAccessToken` is a function. You need to call the function and use the promise that it returns with `await` or `.then()` to get the value from the promise. – jfriend00 Jul 02 '22 at 22:19
  • Well, that seems fine to use .then() or await, but how would i use the access_token globally, i can't get the token out of the then() . – aasir khan Jul 02 '22 at 22:34
  • xy = ac.accessTokenPromise.then(token => console.log(token)); console.log(xy); this gave me "Promise { }" – aasir khan Jul 02 '22 at 22:35
  • 1
    This is basic promise logic. `xy` is the promise. You USE the token INSIDE the `.then()` handler. This is how promises work. You don't get it globally. You can stuff it in a global variable if you want (usually not advised), but you cannot use that global until after the `.then()` handler is called and you will have to make sure of that. – jfriend00 Jul 02 '22 at 22:37

0 Answers0