使用nodejs异步保存到dynamodb

Saving to dynamodb asynchronously using nodejs

本文关键字:dynamodb 保存 异步 nodejs 使用      更新时间:2023-09-26

所以我有以下函数,但当我调用save组件时,只有最后一个条目实际保存到数据库。

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();
}

我如何得到保存被异步调用,使所有条目保存在数据库中?

看起来像是javascript闭包的问题。试一试。

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");
    }
}