我刚开始尝试使用 node 和 knex 构建 Web 应用程序。
请想象我有一个从前端发送的对象数组,我需要将所有数据插入数据库,数组结构如下:
[ { dateTime: 'Aug 08 2019 12:00', event_id: '57' },
{ dateTime: ' Aug 09 2018 12:00', event_id: '57' } ]
Run Code Online (Sandbox Code Playgroud)
表结构如下:
我的想法是使用 for loop & async await 函数来完成这项工作,
我能够使用以下代码插入第一个元素:
addDateTime(dateArray) {
for (let i = 0; i < dateArray.length; i++) {
let tempDateTime = new Date(dateArray[i].dateTime)
return this.knex(dateTimes).insert({
date: tempDateTime.toDateString(),
start_time: tempDateTime.toTimeString().replace("GMT+0800", ""),
iso_string: tempDateTime.toISOString(),
event_id: dateArray[i].event_id
}).returning("event_id");
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用 for loop 和 async await 函数时,我非常困惑和迷茫。
到目前为止我想出的代码没有成功:
addDateTime(dateArray) {
console.log(dateArray);
async function insert(dateArray) {
try{
for (let i = 0; i < dateArray.length; i++) {
let tempDateTime = new Date(dateArray[i].dateTime)
await this.knex(dateTimes).insert({
date: tempDateTime.toDateString(),
start_time: tempDateTime.toTimeString().replace("GMT+0800", ""),
iso_string: tempDateTime.toISOString(),
event_id: dateArray[i].event_id
}).returning("event_id");
}
} catch (err) {
console.log(err);
}
}
insert(dateArray);
}
Run Code Online (Sandbox Code Playgroud)
谢谢你。
您实际上不需要在这里循环,因为knex(...).insert可以轻松接受数组。所以,你需要这样的东西:
async function insert(dateArray) {
try {
const data = dateArray.map(x => {
const tempDateTime = new Date(x.dateTime);
return {
date: tempDateTime.toDateString(),
start_time: tempDateTime.toTimeString().replace("GMT+0800", ""),
iso_string: tempDateTime.toISOString(),
event_id: x.event_id
};
});
await this.knex(dateTimes).insert(data);
} catch (err) {
console.log(err);
}
}
Run Code Online (Sandbox Code Playgroud)
请记住,由于您insert是一个async函数,因此您必须使用 来调用它await,因此您的最后一行应该是await insert(dateArray);,这很可能是您的主要问题。
| 归档时间: |
|
| 查看次数: |
3740 次 |
| 最近记录: |