This might ostensibly look like a duplicate of this one, but it is not.
In the code segment below, I am trying to output myData
from outside the getData()
function:
var myData, obj;
function getData() {
return new Promise(function (resolve, reject) {
fs.readFile('./json/data.json', 'utf8', function (err, data) {
if (err) {
console.log("Error in reading data.json file");
return Promise.reject(err);
}
try{
obj = JSON.parse(data);
}
catch(error) {
console.log('Error in parsing the data.json file');
return Promise.reject(error);
}
obj.forEach(element => {
const options = {
resolveWithFullResponse: true
}
if (element.title == Image) {
rp.get(element.image, options)
.then( function (response) {
if(response.statusCode == 200) {
myData = Buffer.from(response.body).toString('base64');
myData.replace("myData:image/png;base64,", "");
console.log(myData);
console.log('+++++++++++++++++++++++++++++++++');
return Promise.resolve(myData);
}
})
.catch( function(error) {
console.log('Error in downloading the image via request()');
return Promise.reject(error);
})
}
})
});
})
}
getData()
.then(function (myData) {
console.log(myData);
console.log('-----------------------------------------------------');
})
.catch(function (err) {
console.log(err);
console.log('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
});
I am able to get the myData
(above the ++++++
declaration) printed; but not from within the then()
of getData()
below. Why so? How can I get myData
returned via return Promise.resolve(myData);
printed via the then()
of getData()
? I believe this is a case of passing all the way up, a promise within a promise.
Thanks for your help!