javascript - 如何在不重复自己的情况下对我的数据库进行三个调用
问题描述
我正在使用 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);
});
解决方案
在所有可能的方法中,我会说:
如果您想一个接一个地保存所有汽车:
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);
}
推荐阅读
- c - copy_from_user()/__get_user() 在 ioctl 内工作正常,但在 ioctl 外失败
- django - 如何在 django api 中添加计算正确答案的功能?
- firebase - Flutter 和 Firebase 通过查看器 id(与 uid 相同)过滤器将产品附加到用户
- python - python错误消息AttributeError:'Bird'对象没有属性'unsetflapped'
- c# - 如何在 uwp 中使用自动换行优化长文本的渲染性能?
- android - 因为 Aysnc 任务被贬低了我可以使用什么替代方案以及如何使用
- android - 尝试 Bitmap 转换 PDF 文件并尝试将文件保存在 android 的下载目录中
- firebase - 如何使用 Firebase 在 Facebook/Instagram 中的帖子上实现“喜欢/不喜欢”?
- python - 如何在运行时更改 python
- dax - 为什么 DAX 中的这个 SUMX 函数的工作方式与预期不同?