首页 > 解决方案 > 如何在不重复自己的情况下对我的数据库进行三个调用

问题描述

我正在使用 Parse SDK for Javascript 连接到我的数据库并插入三个记录。我的代码有效,但我经常重复自己,我想知道是否有一种更智能、更好的方法来进行这些调用并插入我的数据而不重复代码?这是我的代码:

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

标签: javascript

解决方案


在所有可能的方法中,我会说:

如果您想一个接一个地保存所有汽车:

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

推荐阅读