deep-chat
deep-chat copied to clipboard
requestInterceptor: how to wait before sending request
I'm using sveltekit and I'm trying to use requestInterceptor
to intercept a request. Specifically, I'm trying to wait for some event to happen so some variable changes before I send the request. How can I do that? Thanks!
// +page.svelte
let x = false;
const f = () => {
// do something so x becomes true
}
requestInterceptor={(details) => {
f();
// how to wait for f() to finish running so x becomes true? if x is false, the request should not be sent
if (x) {
return details;
}
}}
Asynchronous operations can be handled using "async, await"
// +page.svelte
let x = false;
const f = async () => {
// do something so x becomes true
}
requestInterceptor={async (details) => {
await f();
// how to wait for f() to finish running so x becomes true? if x is false, the request should not be sent
if (x) {
return details;
}
}}
Great example from @buzhou9! Everything is spot on!
Another way you can test the await
operator is by giving the f
function the following value (the returned Promise
works exactly like @buzhou9's async
):
const f = () => {
return new Promise((resolve) => {
setTimeout(() => {
x = true;
resolve();
}, 2000);
});
}
Thanks both!