1

How do I ensure a promise has resolved in my configuration file. For example my configuration looks like the below.

const fetch = require("node-fetch");

const fetchToken = async () => {
    return await fetch('www.token-endpoint.com', {
        method: "POST",
        headers: {
            ContentType: "application/x-www-form-urlencoded",
        },
        body: new URLSearchParams({
            secret: "this is a secret",
        })
    })
}

const ACCESS_TOKEN = fetchToken()
    .then((res) => { return res.json() })
    .then(...)
    // And so on
    // Now I want my promise to definitely resolve 
    
module.exports = {
    accessToken: ACCESS_TOKEN // This will be undefined unless my promise has resolved
}

After this I would like to use the token.

const config = require("./config")

// Use config.accessToken knowing it is well defined. 
Ivor Denham-Dyson
  • 655
  • 1
  • 5
  • 24
  • You are missing await `const ACCESS_TOKEN = await fetchToken().then((res) => { return res.json() })` – epascarello Sep 01 '20 at 16:45
  • 2
    @epascarello SyntaxError: await is only valid in async function – Ivor Denham-Dyson Sep 01 '20 at 16:46
  • Try to export `fetchToken` method instead of trying to resolve it and export, You can always await it at the call-site – Kunal Mukherjee Sep 01 '20 at 16:47
  • You can't directly. You either have some init function you call earlier, or return a promise. – Keith Sep 01 '20 at 16:50
  • 1
    @epascarello Using await there is useless, it's useful if OP doesn't use the then/catch syntax. – Trisma Sep 01 '20 at 16:54
  • @HereticMonkey not really, unless the answer is you can't do what your trying to do. – Ivor Denham-Dyson Sep 01 '20 at 17:03
  • @HereticMonkey I suppose I am also trying to maintain the variable between JavaScript files which makes things slightly different. Is there perhaps a timeout function that will log an error if the request does not resolve in a certain period. – Ivor Denham-Dyson Sep 01 '20 at 17:08
  • Basically, you can't export the result of an asynchronous call. You can export a Promise, which you can attach to from the importers of the exported libraries, but if it imports after the promise has resolved, you're out of luck. This is why rxjs' Observables were created. – Heretic Monkey Sep 01 '20 at 17:13

1 Answers1

1

you can do something like this ,node fetch actually has a built in function for converting the response to JSON, but it does not do it automatically in the same way that Axios and SuperAgent do. recent versions of this library use promises, so we're able to use async/await syntax with it as well:

const fetch = require('node-fetch');

(async () => {
  try {

    const response = await fetch('www.token-endpoint.com')
    const json = await response.json()

    console.log(json.url);
    console.log(json.explanation);
  } catch (error) {
    console.log(error.response.body);
  }
})();
Leo Bogod
  • 311
  • 1
  • 3
  • 11
  • Thats not what the OP is having problems with – Keith Sep 01 '20 at 17:01
  • he asked how to make sure a promise resolves , this shows how to return a response from async call. – Leo Bogod Sep 01 '20 at 17:04
  • 1
    You maybe mist this bit, `const config = require("./config")`. This will still not work, placing the code inside an IIFE doesn't change that. – Keith Sep 01 '20 at 17:14