尝试使用异步创建控制器,但我不能将匿名函数作为第三个参数传递。我不断收到意外令牌的解析错误{ - '任何想法?如果我直接在params中传递函数(错误,响应),则错误消失。我基本上试图迭代将返回的两个对象,找到每个对象的合同名称,然后分配为该合同分配的数据数组。
var request = require('request'),
helpers = require('../../helpers.js'),
async = require('async');
module.exports.getStatementBreakdown = function(req, res) {
var httpGet,
response,
urls = [
'/financial-advances/',
'/financial-adjustments/'
];
httpGet = function(url, callback) {
var options = helpers.buildAPIRequestOptions(req, url);
request(options,
function(err, res, body) {
var data = {};
if(!err && res.statusCode === 200) {
data = JSON.parse(body);
}
callback(err, data);
}
);
};
response = function(err, responses) {}
async.map(urls, httpGet, response) {
var statementBreakdown = {},
response,
breakdown,
i,
j,
contractName,
key;
for(i = 0; i < responses.length; i++) {
response = responses[i];
for(key in response) {
if(key !== 'meta' || key !== 'notifications') {
breakdown = response[key];
for(j = 0; j < breakdown.length; j++) {
contractName = breakdown[j].reimbursementContract.name;
}
}
}
}
statementBreakdown[contractName] = [];
statementBreakdown[contractName].push(breakdown);
res.send(statementBreakdown);
});
};
答案 0 :(得分:2)
根据您发布的代码示例,您会收到一个意外的令牌,因为您在错误的地方有一个大括号。
见这里:async.map(urls, httpGet, response) {
?那个花括号是意想不到的标记。
当有一个不应该出现的角色时,Javascript会给出一个意外的令牌。在这种情况下,您在函数调用之后立即添加了大括号。在控制流语句和函数声明之后,需要使用大括号。
我不确定你到底想要什么,但也许是这样的?
async.map(urls, httpGet, function(err, responses) {
var statementBreakdown = {},
response,
breakdown,
i,
j,
contractName,
key;
for(i = 0; i < responses.length; i++) {
response = responses[i];
for(key in response) {
if(key !== 'meta' || key !== 'notifications') {
breakdown = response[key];
for(j = 0; j < breakdown.length; j++) {
contractName = breakdown[j].reimbursementContract.name;
}
}
}
}
statementBreakdown[contractName] = [];
statementBreakdown[contractName].push(breakdown);
res.send(statementBreakdown);
});
});
有关async.map的进一步帮助,请参阅docs。