Ad

Node: Fill Config Array From API

- 1 answer

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 }
Ad

Answer

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
});
Ad
source: stackoverflow.com
Ad