如何在不重复自己的情况下对我的数据库进行三次调用

lnlaulya  于 2021-09-23  发布在  Java
关注(0)|答案(3)|浏览(247)

我使用用于javascript的parse sdk连接到我的数据库并插入三条记录。我的代码可以工作,但我经常重复我自己,我想知道是否有一种更聪明、更好的方法可以在不重复代码的情况下进行这些调用并插入数据?这是我的密码:

const Parse = require('parse/node');

Parse.initialize(
    "test",
    "test"
  );

Parse.serverURL = 'url';

const CarObject = Parse.Object.extend("Car");

const firstCar = new CarObject();
const secondCar = new CarObject();
const thirdCar = new CarObject();
firstCar.set("driver", "Sean Plott");
secondCar.set("driver", "Brad Plott");
thirdCar.set("driver", "John Davis");

firstCar.save()
    .then((result) => {
        // Execute any logic that should take place after the object is saved.
        console.info("New object was created with objectId:", result.id);
    }).catch((error) => {
        // Execute any logic that should take place if the save fails.
        // error is a Parse.Error with an error code and message.
        console.error("Error message:", error.message);
    });

    secondCar.save()
    .then((result) => {
        // Execute any logic that should take place after the object is saved.
        console.info("New object was created with objectId:", result.id);
    }).catch((error) => {
        // Execute any logic that should take place if the save fails.
        // error is a Parse.Error with an error code and message.
        console.error("Error message:", error.message);
    });

    thirdCar.save()
    .then((result) => {
        // Execute any logic that should take place after the object is saved.
        console.info("New object was created with objectId:", result.id);
    }).catch((error) => {
        // Execute any logic that should take place if the save fails.
        // error is a Parse.Error with an error code and message.
        console.error("Error message:", error.message);
    });
z18hc3ub

z18hc3ub1#

我更愿意将数据存储在数组中,并使用下面的帮助函数创建对象:

const Parse = require("parse/node");

Parse.initialize("test", "test");

Parse.serverURL = "url";

const CarObject = Parse.Object.extend("Car");

function initCarObject(role, name) {
  const car = new CarObject();
  car.set(role, name);
  return car;
}

const data = [
  { role: "driver", name: "Sean Plott" },
  { role: "driver", name: "Brad Plott" },
  { role: "driver", name: "John Davis" },
];

//Promises in Parallel
function createCarParallel(data) {
  data.map(el =>
    initCarObject(el.role, el.name)
      .save()
      .then(res => console.log(res.id))
      .catch(err => console.log(err))
  );
}

//Promises in Series
async function createCarSeries(data) {
  for (const el of data) {
    try {
      const res = await initCarObject(el.role, el.name).save();
      console.log(res.id);
    } catch (err) {
      console.log(err);
    }
  }
}

createCarSeries(data);
createCarParallel(data);
nszi6y05

nszi6y052#

这似乎足够简洁-将回调拉到单独的函数中,并使用 for...of

const Parse = require('parse/node');
Parse.initialize("test", "test");
Parse.serverURL = 'url';

const CarObject = Parse.Object.extend("Car");

const cars = ["Sean Plott", "Brad Plott", "John Davis"].map((name) => {
  const car = new CarObject();
  car.set("driver", name);
  return car;
});

const onSuccess = (result) => {
  // Execute any logic that should take place after the object is saved.
  console.info("New object was created with objectId:", result.id);
};
const onError = (error) => {
  // Execute any logic that should take place if the save fails.
  // error is a Parse.Error with an error code and message.
  console.error("Error message:", error.message);
};

for (const car of cars) {
  car.save()
    .then(onSuccess)
    .catch(onError);
}
tvmytwxo

tvmytwxo3#

在所有可能的方法中,我想说:
如果您想一辆接一辆地保存所有车辆:

for( let driver of [ "Sean Plott", "Brad Plott", "John Davis"]) {
    const car = new CarObject();
    car.set("driver", driver);
    let result;
    try{
        result = await car.save();
        console.info("New object was created with objectId:", result.id);
    } catch(err) {
        console.error("Error message:", error.message);
    }
}
console.log("All cars saved")

如果您想同时保存所有车辆(速度更快,但会影响数据库,因此只有在没有太多车辆时才使用此选项)

const promises = [ "Sean Plott", "Brad Plott", "John Davis" ].map( driver => {
    const car = new CarObject();
    car.set("driver", driver);
    return car.save // this is a Promise
});

try {
    const result = await Promise.all(promises);
    console.log("All cars saved with ids = ", result.map( r => r.id ) );
} catch(err) {
    console.error("Error message:", error.message);
}

相关问题