1

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();
    }
}
4

2 回答 2

3

执行此操作的标准方法是使用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);
});
于 2013-09-04T23:43:41.067 回答
0

据我所知,在处理异步操作时,您能做的只有这么多。如果你想避免回调,我会说承诺。实际上,我会说无论如何都要使用 Promise :)

于 2013-09-04T23:34:55.650 回答