2017-03-08 10 views
-1

同期AND呼び出しと非同期呼び出しの後にイメージにバウンスエフェクトを作成しようとしていますが、それを行う方法がわかりません。私が今行っている問題は、非同期イベントに時間がかかるため、時々バウンス効果とその後のisExecutedが両方とも得られるということです。非同期呼び出しが完了した後になにかを実行します。

私のコードは次のように動作するはず:myEnum内の各オブジェクトの上

反復をしてmyCondition1があまりにもmyCondition2は設定等しい場合は、次の

  • を実行isExecuted = true
  • 真実ではありません上記の場合、呼び出しいくつかのものを評価する非同期メソッド、それがtrueの場合isExecuted = trueを設定します。
  • 上記をすべて待ってからisExecutedがまだfalseの場合は、画像をバウンスします。

ここでは、コードです:

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がtrueの場合、バウンスチェックは必ず実行されなければならないことに注意してください。

+1

'$(" a "+ index +" img ")'の 'index'はどこから来ますか?これに対する一般的な答えは、約束と 'Promise.all'を使用することです。 –

+0

コールバックが役に立ちますが、私はそれらをjavascriptで書くことについて知らないです –

+0

また、「myVar」とは何ですか? – Tomalak

答えて

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

それは

あなたも、あなたがこれを行うことができ、既存のライブラリを使用することができます。もちろん、
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(); 
    } 
}); 

ようになります。これを達成するためのさまざまな(よりエレガントな)方法があります。

0

代わりに、コールバックを使用します。

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

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

は、これは非常に一般的です。それは、ほとんどの非同期Chrome APISがそれを行う方法です。

関連する問題