0

I need to fill my config object

var config = {
    one: 1,
    two: 2,
    three: /* make an api request here */,
};

with a value of a API-request (http). The API returns a Json string like:

{ configValue: 3 }

How to write a function which fills in the configValue from the API request?

I tried that:

const request = require('request');
var config = {
    one: 1,
    two: 2,
    three: function() {
        request.get('http://api-url',(err, res, body) => {
             return JSON.parse(res.body).configValue;
        };
    }(),
};
console.log(config);

but the result is undefined:

{ one: 1, two: 2, three: undefined }
WeSee
  • 3,158
  • 2
  • 30
  • 58
  • You are missing basic knowledge of JavaScript asynchronous work. Please read this: https://stackoverflow.com/questions/14220321 – yeya Mar 10 '19 at 16:25
  • I'm new to Node, indeed. But this is no browser environment (no Ajax here) but a Node backend server running. How would a Node-like solution look like? – WeSee Mar 10 '19 at 16:34

1 Answers1

1

You need to wait for the request to finish before you start your code.

Try this for example:

const request = require('request-promise-native');

const getConfig = async () => {

    const fromUrl = await request.get('http://api-url');

    return {
        one: 1,
        two: 2,
        three: fromUrl
    }

};

getConfig().then(config => {
    // Do here whatever you need based on your config
});
yeya
  • 1,968
  • 1
  • 21
  • 31
  • Thanks, good hint. But the config-array must be as stated in my question (top-level). I am maintaining an existing software and I cannot change the config-array. So how would a solution look like inside the config array? – WeSee Mar 10 '19 at 16:49
  • Sorry, I can't see any array in your code. If you can't change the code you are maintaining I guess you can't maintain it... – yeya Mar 10 '19 at 16:54
  • Sorry, I mean the config object. – WeSee Mar 10 '19 at 16:55
  • 1
    You can put the async code wherever you want, but the code that depends on it must wait for the request to complete before it get executed... You can do it by `callbacks`, `promises`, ar `aync/await`, your choice. – yeya Mar 10 '19 at 16:56