My apologies as I am very new to javascript and inexperienced so my code is very rudimentary, and I'll do the best I can at explaining myself.
I'm making a call to an API to get a blob which I then convert to base64. I can then pass this base64 string to a seperate script within the .map array - so this makes multiple calls to my script. But what I want to do is to concatenate the base64 strings into one string and pass a single call the my script.
I understand that this is asynchronous and I probably need some callbacks but im unsure how to do this in my case. Essentially I would like to make the 'base64data_1' variable within the reader.onloadend function available outside of the .map array, but the reader.onloadend function is the last action performed.
function getPhoto() {
const root = 'https://public-api.konectech.com/PROD/api/';
var acc = document.getElementById("accID").value;
var photoId1 = document.getElementById("photoID1").value;
var photoId2 = document.getElementById("photoID2").value;
var photoId3 = document.getElementById("photoID3").value;
var root1 = (root + acc + "/attachment/id/overlay/")
let uri = [root1 + photoId1,root1 + photoId2,root1 + photoId3];
let filenames = [photoId1,photoId2,photoId3];
var base64Array = [];
let base64 = uri.map (function (url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.setRequestHeader("accept", "image/jpg");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("x-api-key", "xxxxxxxx");
xhr.responseType = "blob";
xhr.send();
xhr.onload = function (data, filename, mime) {
var filename = (url.slice(url.lastIndexOf('/') + 1) );
const blob = new Blob([this.response], {type: mime || 'application/octet-stream'});
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var base64data = reader.result;
const base64data_1 = (base64data.slice(base64data.lastIndexOf(',') + 1) );
//console.log([base64data_1]);
base64Array = base64data_1;
console.log([base64Array]);
return [base64Array];
};
}
});
//console.log([base64Array]);
}
I was hoping that if i could get access pass the 'base64data_1' variable as an array I could then use promise.all and .join get the desired result similar to below:
function getPhoto() {
var array =['test_1','test_2','test_3','test_4','test_5'];
var items = [];
let newArray = array.map (function (array_1) {
items = array_1 + '_appended';
console.log(items);
return [items];
})
console.log(newArray);
Promise.all(newArray)
.then( function (arrayOfValues) {
console.log(arrayOfValues.join(",")); // returns test_1_appended,test_2_appended,test_3_appended,test_4_appended,test_5_appended
})
}