Effect CommunityEC
Effect Community9mo ago
2 replies
Egor Popov

Working with async 'queue-like' operations in Effect

Hi for every one!

I have a question about working with async operations with Effect

My case:
I have 3 async operations, one of them - polling with 3 seconds, and others - simple requests for backend
Polling run in background and other operations can be fired with user interaction

Problem is that i must not to call Polling operation when on of the others operations not completed

I have stupid and not scalable solution

let runningFirstPromise = null
let runningSecondPromise = null
let runningTimeout = null

const pollingOperation = async () => {
  if (runningTimeout) {
    window.clearTimeout(runningTimeout)
  }  

  if (runningFirstPromise || runningSecondPromise) {
    Promise.all([
      runningFirstPromise,      
      runningSecondPromise
    ]).finally(pollingOperation)

    return;
  }

  // await asyncCall()

  

  runningTimeout = window.setTimeout(pollingOperation, 3000)
}

const firstOperation = async () => {}

const secondOperation = async () => {}


// in some global scope
window.setTimeout(pollingOperation, 3000)

// in some event handler

const runFirstOperation = () => {
  runningFirstPromise = firstOperation()
}


const runSecondOperation = () => {
  runningSecondPromise = secondOperation()
}


How we can work with that case in 'Effect way'?
Was this page helpful?