How to call the same JavaScript function repeatedly while waiting for the function to run its course before invoking it again, using method chaining?

后端 未结 3 1000
暗喜
暗喜 2020-11-30 14:24

Using method chaining, I am looking to fire a function repeatedly but only after the function has completed. Almost like don\'t execute until the function has fully run its

3条回答
  •  独厮守ぢ
    2020-11-30 14:56

    You are looking for Promises, though not supported across the board yet, you can use babel or traceur (or even jQuery's deferred) to use them now:

    var myfunc = {
      copy: function(message) {
        return new Promise(function(resolve, reject) {
          setTimeout(function() {
            resolve(message);
          }, 1000);
        });
      }
    }
    
    // sequential processing
    myfunc.copy('hello').then(function(message1) {
      console.log(message1);
      myfunc.copy('world').then(function(message2) {
        console.log(message2);
      });
    });
    
    // batch processing
    Promise.all([myfunc.copy('hello'), myfunc.copy('world')]).then(function(values) {
      console.log(values.join(' '));
    });
    

    Reference: Promise, Promise.all, Promise.then

提交回复
热议问题