我需要填充我的配置对象
var config = {
one: 1,
two: 2,
three: /* make an api request here */,
};
具有API请求(http)的值。 API返回一个Json字符串,如:
{ configValue: 3 }
如何编写一个从API请求填写configValue
的函数?
我试过了:
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);
但结果是undefined
:
{ one: 1, two: 2, three: undefined }
在开始代码之前,您需要等待请求完成。
试试这个例子:
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
});