各位, 试图解决以下问题。我有一个通过 http.POST 传入的输入数组,我想循环遍历该数组,触发多个 dynamodb 查询,组装输出,然后将此输出作为一个 JSON 对象返回。
我已经验证 POST 工作正常,数组已正确构建,我所需要做的就是发出几个 DynamoDB 调用,组装每个结果,然后返回它。
既然这是异步的,我该如何编写以下内容?
allVehicles: function (req, res, next) {
checkDB(req, res, next)
function checkDB(req, res, next) {
async.each(req.body, lookupDB, function(err) {
console.log("wtf err");
});
returnResponse(callback)
}
function lookupDB(uID) {
var checkUsers = {
TableName : 'tablename',
IndexName : 'license-index',
KeyConditions :
{
"entry":
{
"AttributeValueList" : [
{
"S" : '1'
}
],
"ComparisonOperator" : "EQ"
},
"license" :
{
"AttributeValueList" : [
{
"S" : uID
}
],
"ComparisonOperator" : "EQ"
}
}
}//var
db.query(checkUsers, function(err, data) {
if (err) {
console.log(err)
} else {
if (data.Count > 0) {
console.log("found ", data.Count")
}
}
});//dbq
}
function returnResponse(upstreamData) {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
res.send(JSON.stringify(upstreamData, undefined, 2));
res.end();
}//fun
},
最佳答案
尝试async.map
.
allVehicles: function (req, res, next) {
async.map(req.body, lookup, function(err, results) {
if (err) {
return next(err);
}
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
res.send(JSON.stringify(results, undefined, 2));
res.end();
});
function lookup(id, done) {
db.query({
TableName: 'tablename',
IndexName: 'license-index',
KeyConditions: {
entry: {
AttributeValueList: [{ S: '1' }],
ComparisonOperator: 'EQ'
},
license: {
AttributeValueList: [{ S: id }],
ComparisonOperator: 'EQ'
}
}
}, done);
}
},
关于javascript - NodeJS 结合异步函数的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20791344/