为什么我的异步休息端点返回一个值,但 console.log() 却没有返回值

问题描述 投票:0回答:1

我有一个我想要的场景:

1。将数据插入数据库,从中获取 id,然后

2。将另一组数据插入数据库并从中获取 id。

3.最后,将两个 ID 号插入到映射表中。

我尝试使用 SQLite 在一个事务中执行此操作,并且它有效,但现在我使用 turso(边缘数据库),我遇到了一些奇怪的事情:

异步函数将返回第二次插入的id号 - 但不会

console.log
异步函数中的那些值。但是,我可以 console.log 第一个插入的值。


function buildRouter(env: Env): RouterType {
    const router = Router();

    router.post("/api/main-form", async (request) => {
        const db = buildDB(env)
        const formData = await request.json();

        const loadedFormInfo: any = await db.transaction(async (tx) => {
            // Insert data into formDataTable and retrieve auto-incremented ID
            const insertedFormId: any = tx.insert(formDataTable)
                .values({
                    dateOption: formData.dateOption,
                    timeZone: formData.timeZone,
                    utcTime: new Date(formData.utcTime),
                    localTime: formData.localTime,
                    title: formData.title,
                    tag: formData.tag,
                    latitude: formData.latitude,
                    longitude: formData.longitude,
                    createdAt: new Date()
                })
                .returning({formId: formDataTable.id});
                
            let formId = await insertedFormId.values();
            formId = formId[0].id

            // return formId
           

            // Insert data into proponentsTable using the retrieved formId
            const proponentsData: Proponent[] = formData.proponents;
            let insertedProponentIds: Number[] = [];
            proponentsData.forEach(async proponent => {
                let insertedProponentId = tx.insert(proponentsTable)
                    .values({
                        formId: formId,
                        team: proponent.team,
                        name: proponent.name,
                        email: proponent.email,
                        createdAt: new Date()
                    }).returning({proponentId: proponentsTable.id});

                let proponentId = await insertedProponentId.values();
                proponentId = proponentId[0].id;
                insertedProponentIds.push(proponentId);
            });

            console.log(insertedProponentIds)  // <--- returns an empty array
            return insertedProponentIds // <--- responds with actual array

// third insert would go here //
   
        });

        console.log('outside: ', loadedFormInfo)
        const responseBody = JSON.stringify( {'return_val': loadedFormInfo} );
        const response = new Response(responseBody, { status: 200, headers: { 'Content-Type': 'application/json' } });

        return response;
    });


    
    router.all("*", () => new Response("Not Found.", { status: 404 }));

    return router;

};

这导致最终插入无法获取第二次插入的值的问题 - 因此无法映射...

尝试过一些事情:

           // Insert data into proponentsTable using the retrieved formId
            const proponentsData: Proponent[] = formData.proponents;
            let insertedProponentIds: Number[] = [];
            for (const proponent of proponentsData) {
                try {
                    const insertedProponentId = await tx.insert(proponentsTable)
                        .values({
                            formId: formId,
                            team: proponent.team,
                            name: proponent.name,
                            email: proponent.email,
                            createdAt: new Date()
                        })
                        .returning({ proponentId: proponentsTable.id });
            
                    if (insertedProponentId && insertedProponentId[0] && insertedProponentId[0].id) {
                        const proponentId = insertedProponentId[0].id;
                        insertedProponentIds.push(proponentId);
                    } else {
                        console.error("Invalid insertedProponentId data:", insertedProponentId);
                    }
                } catch (error) {
                    console.error("Error inserting proponent:", error);
                }
            }

            console.log(insertedProponentIds)
            return insertedProponentIds

得到这个:

[mf:inf] POST /api/main-form 500 Internal Server Error (757ms)
⎔ Reloading local server...
[mf:inf] Updated and ready on http://127.0.0.1:8787/
Invalid insertedProponentId data: SQLiteInsert {
  session: _LibSQLSession,
  dialect: SQLiteAsyncDialect,
  config: Object,
  run: ,
  all:
  ...
}
Invalid insertedProponentId data: SQLiteInsert {
  session: _LibSQLSession,
  dialect: SQLiteAsyncDialect,
  config: Object,
  run: ,
  all:
  ...
}
Array(0) [  ]
outside:  Array(0) [  ]
[mf:inf] POST /api/main-form 200 OK (49ms)

javascript sqlite asynchronous cloudflare-workers
1个回答
0
投票

@GolamMoula 谢谢。

这就是我所做的:


            // Insert data into proponentsTable using the retrieved formId
            const proponentsData: Proponent[] = formData.proponents;
            let insertedProponentIds: Number[] = [];
            for (const proponent of proponentsData) {
                try {
                    let insertedProponentId = await tx.insert(proponentsTable)
                        .values({
                            formId: formId,
                            team: proponent.team,
                            name: proponent.name,
                            email: proponent.email,
                            createdAt: new Date()
                        }).returning({ proponentId: proponentsTable.id });
        
                    let proponentId = await insertedProponentId.values();
                    // proponentId = proponentId.map(proponent => proponent.id);
                    proponentId = proponentId[0].id
                    insertedProponentIds.push(proponentId);
                } catch (error) {
                    console.error("Error inserting proponent:", error);
                    throw error;
                }
            }

            console.log(insertedProponentIds)
            return insertedProponentIds
© www.soinside.com 2019 - 2024. All rights reserved.