OvidijusParsiunas / deep-chat

Fully customizable AI chatbot component for your website
https://deepchat.dev
MIT License
1.26k stars 170 forks source link

requestInterceptor: how to wait before sending request #185

Closed hauselin closed 1 month ago

hauselin commented 1 month ago

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

}}
buzhou9 commented 1 month ago

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

}}
OvidijusParsiunas commented 1 month ago

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);
  });
}
hauselin commented 1 month ago

Thanks both!