Search code examples
javascriptjquerychaining

How to have one function wait for another function to finish processing in javascript using chaining?


I have a function that pulls an array from firebase via its rest api, which I need to input into another function to create a calendar.

function array_from_firebase(){
    //code that pulls from firebase
    return array
}

function calendar_create_from_array(array){
    //code that generates calendar
}

The following does not work:

calendar_create_from_array(array_from_firebase())

However, this does work

array = array_from_firebase()
setTimeout(calendar_create_from_array,9000,array)

I believe this means that array_from_firebase takes a bit of time longer than calendar_create_from_array and calendar_create_from_array triggers too quickly.

How could I use chaining and promises to solve this?


Solution

  • From the first function you can return a promise. In this example usage of setTimeout is just to demonstrate that the next function execute after the first function

    function array_from_firebase() {
      return new Promise(
        function(resolve) {
          setTimeout(function() {
            return resolve([1, 2, 3])
          }, 4000)
        },
        function(reject) {})
    }
    
    function calendar_create_from_array(array) {
      console.log(array);
    }
    
    array_from_firebase().then(function(resp) {
      calendar_create_from_array(resp)
    })

    You can also use async & await.In this case the function which will wait for the result from another function need to be declared as async and declare await keyword before the function which will return the result.

    function array_from_firebase() {
      return new Promise(
    
        function(resolve) {
          setTimeout(function() {
            return resolve([1, 2, 3])
          }, 5000)
    
        },
        function(reject) {})
    }
    
    async function calendar_create_from_array() {
      console.log('Calling function and waiting for result for 5secs....')
      let getResult = await array_from_firebase();
      console.log('Got result after 5secs', getResult)
    }
    calendar_create_from_array()