javascriptpromisecallback

Resolve promise on external event


I want to resolve a promise when an event happens in a different function

const trigger = function() {}

const eventHandler = async function() {
  while(true) {
    await new Promise (resolve => {
      
    }
    // Code when the promise fulfills.
  }
}

const cleaner = function() {
  trigger()
}

cleaner()

Solution

  • You can do that really easily by re-assigning the trigger:

    let trigger = () => {}
    
    const eventHandler = async function() {
      while(true) {
        await new Promise (resolve => {
          trigger = resolve
    //    ^^^^^^^^^^^^^^^^^
        }
        // Code when the promise fulfills.
      }
    }
    
    const cleaner = function() {
      trigger() // calls resolve to fulfill the currently waited-for promise
    }
    
    eventHandler() // start waiting
    cleaner()
    

    However, notice that this is generally regarded as a bad practice, you should start whatever leads to the external event, and especially installing the event listener, inside the new Promise executor callback, where you trivially have access to the resolve function.