pull/17004/head
Rich Harris 5 days ago
parent 54cd91f055
commit 1aa3db4641

@ -850,17 +850,18 @@ export function clear() {
/** /**
* @param {() => void} fn * @param {() => void} fn
* @returns {Promise<{ commit: () => void, discard: () => void }>} * @returns {{ commit: () => void, discard: () => void }}
*/ */
export function fork(fn) { export function fork(fn) {
/** @type {Promise<{ commit: () => void, discard: () => void }>} */ if (current_batch !== null) {
const promise = new Promise((fulfil) => { throw new Error('cannot fork here'); // TODO better error
// TODO does qmt guarantee this will run outside a batch? }
// because it needs to
queue_micro_task(async () => {
const batch = Batch.ensure(); const batch = Batch.ensure();
batch.is_fork = true; batch.is_fork = true;
const promise = batch.fork_settled();
flushSync(fn); flushSync(fn);
const deferred_inspect_effects = inspect_effects; const deferred_inspect_effects = inspect_effects;
@ -869,10 +870,8 @@ export function fork(fn) {
source.v = value; source.v = value;
} }
await batch.fork_settled(); return {
commit: async () => {
fulfil({
commit: () => {
if (!batches.has(batch)) { if (!batches.has(batch)) {
throw new Error('Cannot commit this batch'); // TODO better error throw new Error('Cannot commit this batch'); // TODO better error
} }
@ -884,6 +883,8 @@ export function fork(fn) {
} }
} }
await promise;
for (const [source, value] of batch.current) { for (const [source, value] of batch.current) {
source.v = value; source.v = value;
} }
@ -906,9 +907,5 @@ export function fork(fn) {
discard: () => { discard: () => {
batches.delete(batch); batches.delete(batch);
} }
}); };
});
});
return promise;
} }

Loading…
Cancel
Save