Skip to content

Commit

Permalink
Add next ticks before polling instead of after
Browse files Browse the repository at this point in the history
  • Loading branch information
jhugman committed Sep 16, 2024
1 parent 2c5b07f commit a402563
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions typescript/src/async-rust-call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export async function delayPromise(delayMs: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, delayMs));
}

// We'd most likely want this to be a microTask, but hermes doesn't support the
// Javascript API for them yet.
async function nextTickPromise(): Promise<void> {
return new Promise((resolve) => setImmediate(resolve));
}
Expand Down Expand Up @@ -76,16 +78,24 @@ export async function uniffiRustCallAsync<F, T>(
try {
let pollResult: number | undefined;
do {
// Now we have a future, we should prompt some work to happen in Rust.
// We need to make sure we don't poll from the stack frame as we the end of the poll,
// so we wait until the next tick before polling.
await nextTickPromise();

// Calling pollFunc with a callback that resolves the promise that pollRust
// returns: pollRust makes the promise, uniffiFutureContinuationCallback resolves it.
pollResult = await pollRust((handle) => {
pollFunc(rustFuture, uniffiFutureContinuationCallback, handle);
});
// We yield here to allow other tasks to happen between
// the end of the poll and the beginning of the next one.
await nextTickPromise();
pollResult = await pollRust(
(handle) => {
pollFunc(rustFuture, uniffiFutureContinuationCallback, handle);
}
);
} while (pollResult !== UNIFFI_RUST_FUTURE_POLL_READY);

// Now we've finished polling, as a precaution, we wait until the next tick before
// picking up the results.
await nextTickPromise();

// Now it's ready, all we need to do is pick up the result (and error).
return liftFunc(
makeRustCall(
Expand Down

0 comments on commit a402563

Please sign in to comment.