节点:从API填充配置数组

问题描述 投票:0回答:1

我需要填充我的配置对象

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 }
node.js scope callback config
1个回答
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
});
© www.soinside.com 2019 - 2024. All rights reserved.