function createTransaction<T>(config): Transaction<T>
function createTransaction<T>(config): Transaction<T>
定义于: packages/db/src/transactions.ts:74
创建一个新的事务,用于对多个 collection 操作进行分组
• T extends object = Record<string, unknown>
包含 mutation 函数的事务配置
Transaction<T>
新的 Transaction 实例
// Basic transaction usage
const tx = createTransaction({
mutationFn: async ({ transaction }) => {
// Send all mutations to API
await api.saveChanges(transaction.mutations)
}
})
tx.mutate(() => {
collection.insert({ id: "1", text: "Buy milk" })
collection.update("2", draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Basic transaction usage
const tx = createTransaction({
mutationFn: async ({ transaction }) => {
// Send all mutations to API
await api.saveChanges(transaction.mutations)
}
})
tx.mutate(() => {
collection.insert({ id: "1", text: "Buy milk" })
collection.update("2", draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Handle transaction errors
try {
const tx = createTransaction({
mutationFn: async () => { throw new Error("API failed") }
})
tx.mutate(() => {
collection.insert({ id: "1", text: "New item" })
})
await tx.isPersisted.promise
} catch (error) {
console.log('Transaction failed:', error)
}
// Handle transaction errors
try {
const tx = createTransaction({
mutationFn: async () => { throw new Error("API failed") }
})
tx.mutate(() => {
collection.insert({ id: "1", text: "New item" })
})
await tx.isPersisted.promise
} catch (error) {
console.log('Transaction failed:', error)
}
// Manual commit control
const tx = createTransaction({
autoCommit: false,
mutationFn: async () => {
// API call
}
})
tx.mutate(() => {
collection.insert({ id: "1", text: "Item" })
})
// Commit later
await tx.commit()
// Manual commit control
const tx = createTransaction({
autoCommit: false,
mutationFn: async () => {
// API call
}
})
tx.mutate(() => {
collection.insert({ id: "1", text: "Item" })
})
// Commit later
await tx.commit()
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。