我是Node.js的新手,我遇到了问题。
我想从我从github API下载的JSON对象中保存数据。
var http = require("http");
var express = require('express');
var app = express();
var github = require('octonode');
var client = github.client();
app.set('port', process.env.PORT || 8000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
app.get('/getUsers', function (req, response) {
response.writeHead(200, {'Content-Type': 'text/json'});
var result;
client.get('/users/angular/repos', {}, function (err, status, body, headers) {
result = response.write(JSON.stringify(body));
console.log(result); //JSON object
return result;
});
console.log(result); //undefined
});
如何将数据从对象保存到单个变量?
(我想将其转换为数组并获取一些有用的数据)。
答案 0 :(得分:0)
您将无法获得异步调用之外的结果,因为它尚未定义。要获取此值,请在查询回调中调用方法,或使用异步模块并传递它。
app.get('/getUsers', function (req, response) {
response.writeHead(200, {'Content-Type': 'text/json'});
var result;
client.get('/users/angular/repos', {}, function (err, status, body, headers) {
result = response.write(JSON.stringify(body));
console.log(result); //JSON object
doSomeOperationOnResult(result)
});
});
function doSomeOperationOnResult(result){
//Your operating code
}