If this section of the code:
if (source !== "itunes"){
getCustomCover(title);
}
else {
getiTuensCover(iTunes_data);
}
is inside the for each, then you might need a promise if you're gonna pass all the result at the same time. But in case your usage of cover can be done async without affection your application, then you might need a Callback Pattern. For example, modify your function to something like this :
var getCustomCover = function (title, callback) {
var jsonFile = './jsonfile.json';
fs.readFile(filePath, (err, data) => {
if (err) {
callback(err);
} else {
var json = JSON.parse(data.toString());
var cover = json['title'].cover;
callback(null, cover);
}
});
};
Change it according your need. Then call your function :
if (source !== "itunes"){
getCustomCover(title, (err, coverUrl) => {
if (err) {
console.log(err);
} else {
updateCover(coverUrl);
}
});
}
else {
// DO THE SAME IF NECCESSARY HERE
getiTuensCover(iTunes_data);
}
This is an Error-First Callback pattern that is standard in NodeJS.
EDIT --------------
To adapt to the code you just added :
function getCustomCover(currentTitle, callback){
$.each(cover_data, function( key, value ) {
if (value.title === currentTitle){
currentCoverURL = value.image;
} else {
currentCoverURL = settings.default_image;
}
callback(currentCoverURL);
});
}
This way the callback function will be called with currentCoverURL
arguments as many times as there is covers in the loop.
EDIT 2 -------------
I you're expecting to find only one coverURL inside the loop, then you might consider refactoring you're code like this :
function getCustomCover(currentTitle, callback){
currentCoverURL = settings.default_image;
$.each(cover_data, function( key, value ) {
if (value.title === currentTitle){
currentCoverURL = value.image;
}
});
callback(currentCoverURL);
}