user3236101
user3236101

Reputation: 78

Saving to dynamodb asynchronously using nodejs

So I have the following function but when I call save component only the last entry is actually saving to the database.

var shortid = require('shortid'),
 dynamodb = new AWS.DynamoDB();


    setupComponents: function(args) {
                    console.log(args)
                      if (args["componentName"] &&  args["apiKey"] !== null){
                          var apiKey = args["apiKey"]
                          for (i = 0; i < args["componentName"].length; i++) {
                            console.log(args["componentName"][i]);
                            var componentName = args["componentName"][i];
                            saveComponent(componentName, apiKey);
                          }
                      } else {
                          console.log("NULL FOUND");
                      }
                  },

function saveComponent(args, apiKey) {
    var o = new SoftwareComponent({
      _id: shortid.generate,
      componentName: args,
      versionName: "default",
      stepName: "default",
      timeInMS: "default",
      stepResult: "default",
      notes: "default",
      apiKey: apiKey
    });
    console.log(o)
    o.save();
}

How would I get save to be called asynchronously so all entries save in the database?

Upvotes: 0

Views: 62

Answers (1)

Dan Beaulieu
Dan Beaulieu

Reputation: 410

Looks like an issue with javascript closures. Try.

setupComponents: function (args) {
    console.log(args);
    if (args["componentName"] && args["apiKey"] !== null) {
        var apiKey = args["apiKey"];
        var arr = args["componentName"];
        arr.forEach(function(item, index){
            console.log(item);
            saveComponent(item, apiKey);
        });
    } else {
        console.log("NULL FOUND");
    }
}

Upvotes: 1

Related Questions