M
M
Misha Kogan2015-09-02 18:46:52
JavaScript
Misha Kogan, 2015-09-02 18:46:52

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

3 answer(s)
A
Alexander Prozorov, 2015-09-02
@Kogan4ik

For these purposes, use the async library . Specifically async.each(arr, iterator, [callback]) .

D
Dmitry Kravchenko, 2015-09-02
@mydearfriend

forEach is synchronous

[1,2,3].forEach(function(item){
  console.log(item)
});
console.log(4)
//1 2 3 4

update:
You are using asynchronous functions in the loop. You can replace forEach with a map, collect an array of promises, and write something like Promise.all(promises).then(function(){/*code below*/});

I
Ivan Zmerzlyi, 2015-09-03
@DangelZM

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

Example here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question