Answer the question
In order to leave comments, you need to log in
How to call callback after forEach execution?
How to call callback after forEach execution?
That is, I went through the entire array and then performed a certain action, otherwise it turns out that the code starts to run further, and I need synchronous execution.
items.forEach(function(item) {
var newItem = new Item();
newItem.name = item.name;
newItem.icon_url = item.icon_url;
newItem.icon_url_large = item.icon_url_large;
newItem.type = item.type;
community.getMarketItem(item.appid, item.market_hash_name, function(err, item) {
if(err) throw err;
newItem.lowestPrice = item.lowestPrice;
logger.info('Get price');
newItem.save(function(err) {
if(err) throw err;
logger.info(' New Item saved!');
});
});
newBet.item.push(newItem);
});
// нужно чтобы этот код выполнялся после цикла
newBet.save(function(err) {
if(err) throw err;
logger.info(' New Bet saved!');
});
Answer the question
In order to leave comments, you need to log in
For these purposes, use the async library . Specifically async.each(arr, iterator, [callback]) .
forEach is synchronous
[1,2,3].forEach(function(item){
console.log(item)
});
console.log(4)
//1 2 3 4
var resultHolder = document.querySelector('#result');
var result = '';
[1,2,3,4,5].forEach(function(item, index, arr) {
result += index + ':' + item + '<br>';
if(index === arr.length-1)
resultHolder.innerHTML = result;
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question