سؤال

Folks, I am writing an API function that needs to make several calls to the back-end DynamoDB tables. The returned JSON results need to be combined, then returned back to the caller as a single response. How would I write this, since I seem to not be completely writing this async...

So far, I've been able to write the function to make a single call, then return it. How would I program a second db.query?

var restify = require('restify');
var fs = require('fs');
var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});
var db = new AWS.DynamoDB();

module.exports = {
    license: function (req, res, next) {
        var params = {
            TableName : 'tableA',
            KeyConditions : 
            {
                "myHashKey":
                {
                    "AttributeValueList" : [
                    {
                        "S" : "1"
                    }
                    ],
                    "ComparisonOperator" : "EQ"
                },
                "myRangeKey" : 
                {
                    "AttributeValueList" : [
                    {
                        "S" : req.params.rangekeyA
                    }
                    ],
                    "ComparisonOperator" : "EQ"
                }
            }
        }

        data = db.query(params, function(err, data) {
            if (err) {
                console.log(err);
                    } 
            else {
                res.statusCode = 200;
                res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
                res.send(JSON.stringify(data, undefined, 2));
                res.end();
            }
        });
        return next();
    },
};

Is async.js https://github.com/caolan/async something I should look into?

هل كانت مفيدة؟

المحلول

Rather than send that info back at this line:

res.send(JSON.stringify(data, undefined, 2));

Define another function, below, such as:

function nextDBQuery(data)
    //query db, do more stuff, yada yada,
    //pass on to another similar function
}

And send your data there with:

nextDBQuery(data);

Basically, instead of res.send() ing your first set of data, pass it on to another function, or just do all the work inside there and have a lot of callbacks.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top