Answer the question
In order to leave comments, you need to log in
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);
}
});
});
Answer the question
In order to leave comments, you need to log in
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) => {...});
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);
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 questionAsk a Question
731 491 924 answers to any question