Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

79
Views
javascript : How do I make a function wait for another to complete?

I have some code similar to this :

$(function() {
  var focusOutEvent = function() {
    $.when(
      getCounterValue()
    ).done(function() {
      console.log('catchValidateButtonClick');
    });
  }

  var getCounterValue = function() {
    $.when(
      console.log('updateCacheData')
    ).done(function() {
      computeCounterValue(function() {
        console.log('counterValueComputation done');
      });
    });
  }

  var computeCounterValue = function(callback) {
    setTimeout(function() {
      callback();
    }, 3000);
  }

  focusOutEvent();
});

Currently, the console prints statements in this order :

  • "updateCacheData"
  • "catchValidateButtonClick"
  • "counterValueComputation done"

How do I make the console print "counterValueComputation done" before "catchValidateButtonClick" ?

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

Make getCounterValue return a Promise. Here's an example with minimal changes:

  var getCounterValue = function() {
    return $.when(
      console.log('updateCacheData')
    ).then(function() {
      let d = $.Deferred();
      computeCounterValue(function() {
        console.log('counterValueComputation done');
        d.resolve();
      });
      return d;
    });
  }

Here's a cleaner way to do it:

  var getCounterValue = function() {
    return $.when(
      console.log('updateCacheData')
    ).then(function() {
      return computeCounterValue().then(function() {
        console.log('counterValueComputation done');
      });
    });
  }

  var computeCounterValue = function() {
    return new Promise(resolve => setTimeout(resolve, 3000));
  }

And here's what it could look like with async/await.

$(function() {
  var focusOutEvent = async function() {
    await getCounterValue();
    console.log('catchValidateButtonClick');    
  }

  var getCounterValue = async function() {
    console.log('updateCacheData');
    await computeCounterValue();
    console.log('counterValueComputation done');    
  }

  var computeCounterValue = function() {
    return new Promise(resolve => setTimeout(resolve, 3000));
  }

  focusOutEvent();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs