我可能对 Node.js 的异步性有一些问题。
休息.js
var Shred = require("shred");
var shred = new Shred();
module.exports = {
Request: function (ressource,datacont) {
var req = shred.get({
url: 'ip'+ressource,
headers: {
Accept: 'application/json',
},
on: {
// You can use response codes as events
200: function(response) {
// Shred will automatically JSON-decode response bodies that have a
// JSON Content-Type
if (datacont === undefined){
return response.content.data;
//console.log(response.content.data);
}
else return response.content.data[datacont];
},
// Any other response means something's wrong
response: function(response) {
return "Oh no!";
}
}
});
}
}
其他.js
var rest = require('./rest.js');
console.log(rest.Request('/system'));
问题在于,如果我从 other.js 调用请求,我总是会得到“未定义”。如果我在 rest.js 中取消注释 console.log,则 http 请求的正确响应将写入控制台。我认为问题在于该值是在请求的实际响应出现之前返回的。有谁知道如何解决这个问题?
最好的,dom