代码之家  ›  专栏  ›  技术社区  ›  plat123456789

js:如何用for循环插入多个数据?

  •  2
  • plat123456789  · 技术社区  · 8 年前

    我对尝试用node&knex构建web应用程序的编码还很陌生。

    请假设我有一个从前端发送的对象数组,我需要将所有数据插入数据库,数组结构如下:

    [ { dateTime: 'Aug 08 2019 12:00', event_id: '57' },
    { dateTime: ' Aug 09 2018 12:00', event_id: '57' } ]
    

    表格结构如下:

    table structure

    我的想法是使用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");
            }
    

    但当我尝试使用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);
    }
    

    谢谢您。

    1 回复  |  直到 8 年前
        1
  •  0
  •   bredikhin    8 年前

    你不需要在这里兜圈子 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);
        }
    }
    

    记住,自从你 insert 是一个 async 函数,你必须调用它 await ,所以你的最后一行应该是 await insert(dateArray); 这很可能是你的主要问题。