Answer the question
In order to leave comments, you need to log in
How to output variables from async.eachSeries function?
Good afternoon, there are 2 cycles with requests that form 2 arrays, I display them in two different callbacks, but I need to combine them into one after successfully processing one and the other, but I can’t get it out
async.eachSeries(result, function(item, callback2) {
request.get("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist="+encodeURIComponent(item['artist'])+"&api_key=xxxx&format=json", function(err, res, body)
{
if(res.statusCode == 200 ) {
if(JSON.parse(body)['artist'] !== undefined) {
temp2.push({name: count2, number: JSON.parse(body)['artist']['image'][2]['#text']});
}
else {
temp2.push({name: count2, number: false});
}
callback2();
count2++;
}
else {
callback2('Error');
}
});
},
function(err) {
if( err ) {
console.log('Ошибка случилась');
} else {
console.log('Все хорошо едем дальше');
console.log(temp2);
}
});
Answer the question
In order to leave comments, you need to log in
You still chose async. It will look terrible, but you can use caolan.github.io/async/docs.html#parallel. Sleep these two eachSeries in parallel, and where 'we go further' is displayed, call parallel'evskiy callbak with your array. At the end, when parallel completes, it will contain both of your arrays.
Written terribly, and in the code will look even worse. I categorically do not recommend you to use this ancient five-year-old approach. It's 2017, so it's time to take the courage to learn Promise and other goodies of modern javascript. Good advice here.
This is how I wrote it, in general, if this script is executed with if, then mysql crashes instantly
result.forEach(function(item){
wp.song().search( item['artist']+' - '+item['song'] ).then(function( posts ) {
if(!posts[0]){
var myRequests = [];
myRequests.push(rp({uri: "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist="+encodeURIComponent(item['artist'])+"&api_key=*****&format=json", json: true}));
myRequests.push(rp({uri: "https://www.googleapis.com/youtube/v3/search?part=snippet&order=viewCount&q="+encodeURIComponent(item['artist']+'+'+item['song'])+"&type=video&key=***", json: true}));
Promise.all(myRequests)
.then((arrayOfHtml) => {
console.log(arrayOfHtml[0]['artist']['image'][2]['#text']);
console.log(arrayOfHtml[1]['items'][0]['id'].videoId);
wp.posts().create({
title: item['artist']+' - '+item['song'],
content: 'Your post content',
status: 'publish'
}).then(function( response ) {
console.log( response.id );
})
})
.catch(/* handle error */);
}
});
})`
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question