为什么我的异步 REST 端点返回一个值,而不是 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
投票

这就是我所做的:

// 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.