节点:从 API 填充配置数组

Node: fill config array from API

我需要填写我的配置对象

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

具有 API 请求 (http) 的值。 API returns 一个 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
});