异步调用完成后才做些什么

问题描述:

我试图在同步和异步调用后的图像上创建反弹效果,但无法弄清楚如何去做。我现在遇到的问题是,我有时会同时获得反弹效果,之后isExecuted会变为true,因为异步事件需要一些时间。异步调用完成后才做些什么

我的代码应该像这样工作:

遍历每个对象myEnum并执行以下

  • 如果myCondition1等于太myCondition2设置isExecuted = true
  • 如果上面是不是真的,叫异步方法评估一些东西,如果它是真的,它将设置isExecuted = true
  • 等待所有以上完成,然后如果isExecuted还是假的,弹跳图像。

下面的代码:

var isExecuted = false; 

myEnum.each() 
{ 
    if (myCondition1 == myCondition2) { //Synchronous 
     isExecuted = true; 
     return false; //stop the iteration 
    } 
    else { 
     MyAsyncFunction(myCondition2, function(isTrue) { // Asynchronous 
      if (isTrue) { 
       isExecuted = true; 
       return false; //stop the iteration 
      }     
     }); 
    } 
}); 

// Execute this ONLY when above code is finished executing 
if (isExecuted == false) { 
    BounceImage(); 
} 

请注意异步函数并不总是执行,但如果isExecuted是真的必须要执行的反弹检查。

+1

'$(“a#”+ index +“img”)''中的'index'来自哪里?通用答案是:使用promise和'Promise.all'。 –

+0

回调可以帮助,但我不知道写在javascript –

+0

此外,什么是'myVar'? – Tomalak

这整个设置不会按照您的要求工作,因为您无法停止异步回调的迭代。相反,你必须异步处理数组(或任何myEnum),然后做一些事情。我强烈建议您了解promises

function process(array, cb) { 
 
    var i = 0; 
 
    
 
    function p(v) { 
 
    return new Promise((resolve, reject) => { 
 
     try { 
 
     // call the callback, passing in the current value and 
 
     // a callback to control execution 
 
     cb(v, function next(stop, result) { 
 
      if (stop) { 
 
      // if stop = true, abort the iteration and resolve the passed in value 
 
      resolve(result); 
 
      } else if (i < array.length) { 
 
      // else if there are more elements left, process them 
 
      resolve(p(array[i++])); 
 
      } else { // else resolve to the passed in value 
 
      resolve(result); 
 
      } 
 
     }); 
 
     } catch(e) { 
 
     reject(e); 
 
     } 
 
    }); 
 
    } 
 
    
 
    // start with the first element 
 
    return p(array[0]); 
 
} 
 

 
process([1,2,3], function(v, next) { 
 
    if (v == 2) { 
 
    return next(true, v); 
 
    } 
 
    next(); 
 
}).then(result => console.log(result));

应用到你的代码,它会看起来像

process(myEnum, function(v, next) { 
    if (myCondition1 == myCondition2) { 
    return next(true, true); 
    } else { 
    MyAsyncFunction(myCondition2, function(isTrue) { 
     if (isTrue) { 
     return next(true, true); 
     } 
     next();     
    }); 
    } 
}).then(function(isExecuted) { 
    if (!isExecuted) { 
    BounceImage(); 
    } 
}); 

当然你也可以使用现有的库,可以让你做到这一点。有许多不同(可能更优雅)的方式来实现这一点。

相反,使用回调:

function asyncFunction (a, b, c, callback) { 
    ... 
    callback(); 
} 

asyncFunction(1, 2, 3, function() { 
    doSomethingOnceDone(); 
}); 

这是一个非常普遍的做法。这就是大多数异步Chrome APIS所做的,仅仅是为了说明一件事。