【问题标题】:Node: fill config array from API节点:从 API 填充配置数组
【发布时间】:2019-03-10 16:00:08
【问题描述】:

我需要填写我的配置对象

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 }

【问题讨论】:

  • 您缺少 JavaScript 异步工作的基本知识。请阅读:stackoverflow.com/questions/14220321
  • 我确实是 Node 新手。但这不是浏览器环境(这里没有 Ajax),而是运行的 Node 后端服务器。类似 Node 的解决方案会是什么样子?

标签: node.js scope callback config


【解决方案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
});

【讨论】:

  • 谢谢,很好的提示。但是配置数组必须如我的问题(顶级)中所述。我正在维护现有软件,但无法更改配置数组。那么解决方案在配置数组中会是什么样子呢?
  • 抱歉,我在您的代码中看不到任何数组。如果您无法更改正在维护的代码,我想您无法维护它...
  • 对不起,我的意思是配置对象。
  • 你可以把异步代码放在你想要的任何地方,但是依赖它的代码必须等待请求完成才能执行...你可以通过callbacks,@987654323来做@, ar aync/await, 你的选择。
猜你喜欢
  • 2018-03-28
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多