尝试使用异步创建控制器,但是我无法将匿名函数作为第三个参数传递。我不断收到意外令牌的解析错误{-'有什么想法吗?如果我直接在参数内部传递function(err,response),错误就会消失。我基本上是想遍历将要返回的两个对象,为每个对象找到一个合同名称,然后分配一个为该合同分配的数据数组。
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);
});
};
最佳答案
根据您发布的代码示例,您得到了意外的令牌,因为您在错误的位置放了大括号。
看到这里: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。
关于javascript - Node Controller -异步传递匿名功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38353872/