deep-chat icon indicating copy to clipboard operation
deep-chat copied to clipboard

requestInterceptor: how to wait before sending request

Open hauselin opened this issue 9 months ago • 2 comments

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;
    }

}}

hauselin avatar May 05 '24 23:05 hauselin

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;
    }

}}

buzhou9 avatar May 15 '24 06:05 buzhou9

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);
  });
}

OvidijusParsiunas avatar May 16 '24 00:05 OvidijusParsiunas

Thanks both!

hauselin avatar May 20 '24 03:05 hauselin