Ad
Node: Fill Config Array From API
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
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error
Ad