简体   繁体   中英

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" ?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM