【发布时间】:2018-11-08 22:18:33
【问题描述】:
我知道以前有很多类似的问题,但我已经尝试了每一个,但每次尝试仍然遇到这个特定问题。所以我正在做的是我有一个名为 data.js 的文件,其中包含一个从 web api 获取 json 数据并返回 Json 解析字符串的函数。我有另一个调用此函数的文件,只是我试图在控制台上调试结果。但是每次我运行该函数时,我都会在控制台上得到“未定义”,即代码是异步运行的,并且在获取之前就返回了值。 这是我的代码:
数据.js
module.exports = {
holidays: function(x,y,z)
{
function intialize()
{
return new Promise(function(resolve, reject) {
Request.post({
"headers": { "content-type": "application/json" },
"url": //someurl,
"body": JSON.stringify({//some input})
}, function(err, resp, body) {
if (err)
{
reject(err);
}
else
{
resolve(JSON.parse(body));
}
})
})
}
var Request = require("request");
var json_content="";
var req = intialize();
req.then(function(result) {
console.log(result);//getting correct answer here
json_content=result;
//I know I've to return the value somewhere here but how do i do it
}, function(err) {
console.log(err);
});
return(json_content);
}
};
调用函数中的代码:
var h= require(__dirname+'/data.js');
console.dir(h.holidays('x','y','z'));//getting undefined
【问题讨论】:
标签: node.js promise request async-await node-modules