Javascript - Wait the true ending of a function th

2019-08-03 05:38发布

Let me explain my problem with a dummy situation. Let's consider the following code :

var counter = 0;    
function increase(){
    if(counter < 10){
        counter++;
        setTimeout(increase, 100);
    }
}

Now, the idea is to display the counter value once the increase() function has finished its job. Let's try this :

increase();
alert(counter);

As you probably know, it doesn't work. The alert() call displays 1, not 10. I would like to display the value of counter once the function has entierly finished its job of incrementing it.

Is there a simple way to solve my problem ?

[Note] Using a callback function is NOT an option, since I don't want increase() to know that I would like to do something after it's done (for modularity purposes). So, I'd like to AVOID something like this :

function increaseForTheKings(f){
    if(counter < 10){
        counter++;
        setTimeout(function(){ increase(f); }, 100);
    } else {
       f();
    }
}

2条回答
做个烂人
2楼-- · 2019-08-03 06:00

The standard way to do this is with promises.

var counter = 0;
function increase(){
  var d = jQuery.Deferred();
  var doIncrease = function() {
    if(counter < 10){
        counter++;
        setTimeout(doIncrease, 100);
    } else {
      d.resolve();
    }
  };
  doIncrease();
  return d.promise();
};

increase().then(function() {
  alert(counter);
});
查看更多
霸刀☆藐视天下
3楼-- · 2019-08-03 06:00

As far as I know, there's only so much you can do when dealing with asynchronous operations. If you want to avoid a callback, I'd say go with promises. Actually, I'd say use promises anyway :)

查看更多
登录 后发表回答