仅在异步调用完成后执行某些操作

时间:2017-03-08 17:15:26

标签: javascript asynchronous

我尝试在同步和异步调用之后在图像上创建一个反弹效果,但无法弄清楚如何操作。我现在遇到的问题是,我有时会同时获得跳出效果,之后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}}为真,则必须始终执行退回检查。

2 个答案:

答案 0 :(得分:1)

这整个设置无法正常工作,因为您无法停止异步回调的迭代。相反,你必须异步处理数组(或任何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));
&#13;
&#13;
&#13;

应用于您的代码,它看起来像

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

当然,您也可以使用现有的库来执行此操作。有许多不同的(可能更优雅的)方法来实现这一目标。

答案 1 :(得分:0)

相反,请使用回调:

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

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

这是一种非常常见的做法。大多数异步Chrome APIS都是这样做的,仅举几例。

相关问题