2015-11-27 60 views
0

我想对数组做一些思考:在添加新的参数检查后使用skinydobazy。如何在javascript中执行同步性

skinydobazy.forEach(function(klucz,index) { 
    getPrice(data.prices[0]).then(function(results) { 

      var price = results.skinData.wep.median_price; 
      if(price > 1) 
      klucz.check = 1; 

      console.log('HERE'); 

     }); 
    }); // end foreach 


    console.log(skinydobazy); //do sth after foreach 

(在foreach循环之后)我想对更新skinydobazy做一些思考。但我有一个问题。因为第一次显示skinydobazy,但应该“这里”,之后应显示skinydobazy。

是否有解决方案? 谢谢

回答

1

通过使用map而不是forEach,您可以生成一个Promises数组。然后您可以使用Promise.all订阅该阵列中所有Promise的完成。

Promise.all(skinydobazy.map(function(klucz, index) { 
    // Return the Promise that resolves on .then(fn) 
    return getPrice(data.prices[0]).then(function(results) { 

    var price = results.skinData.wep.median_price; 
    if (price > 1) 
     klucz.check = 1; 

    console.log('HERE'); 

    // Resolve Promise with results 
    return results; 
    }); 
}).then(function(allResults) { 
    // allResults will be an array of results 
    console.log(skinydobazy); 
});