节点:从API填充配置数组

时间:2019-03-10 16:00:08

标签: node.js scope callback config

我需要填写我的配置对象

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 }

1 个答案:

答案 0 :(得分:1)

在启动代码之前,您需要等待请求完成。

尝试以下示例:

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
});