The callback function you provide to then
is indeed executed asynchronously, which means it is only executed after the rest of the code in the current call stack has finished executing, including your final console.log
.
Here is how you could do it:
function getAlbumsTotal(list, params){
var promises = list.map(function (item) { // return array of promises
// return the promise:
return api.getArtistAlbums(item, params)
.then(function(data) {
for(var alb = 0; alb<data.body.items.length; alb++){
albums.push(data.body.items[alb].id);
}
}, function(err) {
console.error(err);
});
});
Promise.all(promises).then(function () {
console.log(albums);
//do something with the finalized list of albums here
});
}
NB: Apparently albums
is defined as a global variable. This is not so good a design. It would be better that each promise would provide its own subset of albums, and the Promise.all
call would be used to concatenate those results into a local variable. Here is how that would look like:
function getAlbumsTotal(list, params){
var promises = list.map(function (item) { // return array of promises
// return the promise:
return api.getArtistAlbums(item, params)
.then(function(data) {
// return the array of album IDs:
return Array.from(data.body.items, function (alb) {
return alb.id;
});
}, function(err) {
console.error(err);
});
});
Promise.all(promises).then(function (albums) { // albums is 2D array
albums = [].concat.apply([], albums); // flatten the array
console.log(albums);
//do something with the finalized list of albums here
});
}
0
Created by trincot on 2020-03-14 08:00:13 +0000 UTC
Share