【发布时间】: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