N
N
nezzard2016-12-14 18:05:12
Node.js
nezzard, 2016-12-14 18:05:12

How to delay loop in node.js?

Good evening, please tell me how to implement a delay in a request of this type

result.forEach(function(items) {
      request.get("https://www.googleapis.com/youtube/v3/search?part=snippet&order=viewCount&q="+items['song']+'+'+items['song']+"&type=video&key=AIzaSyAvDAdEnqrStOJNnpnGy9BkrC_sG-gcHIU", function(err,res,body){
          if(res.statusCode == 200 ) {          	
             console.log(JSON.parse(body)['items'][0].id.videoId);	         
          }
      });
  });

The problem is that the response from the server comes, everything works, but it comes every time in a different order.
Most likely this is due to the fact that Google servers process requests at different speeds and based on a different sequence of outputted data.
But I need it strictly in order, tell me how to make the delay.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly, 2016-12-14
@vitali1995

I advise you to study Promise. Before the loop, a Promise instance is created, each iteration is signed by the then method for the next request. After the loop, you can add the last then to the promise, which will continue to execute the task when the last request is received. When the function completes, the event loop begins to sequentially execute the requests added by the Promise.
Looks like this:

let promise = Promise.resolve();
for(...) {
  promise.then( () => {
    return new Promise((resolve) => {
      request.get(..., (data) => {... resolve(data);});
    }
  }
}
promise.then((lastData) => {...});

D
Dark Hole, 2016-12-14
@abyrkov

Abandon forEach... more precisely, use for in the generator instead.

function* code(result) {
  for(var i = 0; i < result.length; i++) yield result[i];
}
function code2(gen) {
  items = gen.next().value;
  request.get("https://www.googleapis.com/youtube/v3/search?part=snippet&order=viewCount&q="+items['song']+'+'+items['song']+"&type=video&key=AIzaSyAvDAdEnqrStOJNnpnGy9BkrC_sG-gcHIU", function(err,res,body){
          if(res.statusCode == 200 ) {          	
             console.log(JSON.parse(body)['items'][0].id.videoId);	
             code2(gen);         
          }
      });
}
let gen = code(result);
code2(gen);

A
Anton L, 2016-12-14
@antonecma

If you don't like ES6 (for nothing, by the way), use the good old async module.

npm i async --save

var items = []; //здесь ваш массив
async.eachSeries(items, function(item, callback) {
      request.get("https://www.googleapis.com/youtube/v3/search?part=snippet&order=viewCount&q="+item['song']+'+'+item['song']+"&type=video&key=AIzaSyAvDAdEnqrStOJNnpnGy9BkrC_sG-gcHIU", function(err, res, body){
          if(res.statusCode == 200 ) {          	
             console.log(JSON.parse(body)['items'][0].id.videoId);	
             callback();
          } else {
              callback('Error');
          }
        
      });    
}, function(err) {
    if( err ) {
            console.log('Ошибка случилась');
          } else {
      console.log('Все хорошо едем дальше');
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question