You have made a mistake with the async/await usage - please refer to the comments in the code below
var allSVGElements = [];
async function addAllKanji(){
let fileNames = ["0f9a8","064e3","05ae1","05afa","062ac","062c8"];
// change to Promise.all
return await Promise.all(fileNames.map(function (fileName) {
// return something
return fetchKanji(fileName);
}));
}
function fetchKanji(name){
// return the promise
return fetch(`http://localhost:8080/public_html/static/kanjiSVG/${name}.svg`,{
method: "GET",
}).then(response => drawSVG(response))
.catch(error => {
throw error;
});
}
async function drawSVG(svg) {
let svgRawText = await svg.text();
svgRawText = svgRawText.replace(/[\s\S]*(?=<svg)/,"");
allSVGElements.push(svgRawText);
}
//doesn't need to be async
function addKanjiToHTML() {
console.log("length: "+allSVGElements.length);
console.log(allSVGElements);
console.log("length: "+allSVGElements.length);
allSVGElements.forEach(function (ele) {
console.log(ele);
console.log("running forEach")
});
}
A more concise and well-written version of your code would be:
function addAllKanji() {
let fileNames = ["0f9a8","064e3","05ae1","05afa","062ac","062c8"];
return Promise.all(fileNames.map(fetchKanji));
}
function fetchKanji(name){
// return the promise
return fetch(`http://localhost:8080/public_html/static/kanjiSVG/${name}.svg`, {method: "GET"}).then(drawSVG)
}
async function drawSVG(svg) {
let svgRawText = await svg.text();
return svgRawText.replace(/[\s\S]*(?=<svg)/,"");
}
addAllKanji().then(allSVGElements => {
console.log("length: "+allSVGElements.length);
console.log(allSVGElements);
console.log("length: "+allSVGElements.length);
allSVGElements.forEach(function (ele) {
console.log(ele);
console.log("running forEach")
});
});
This updated version also includes the functionality of addKanjiToHTML
at the end.
In my opinion, in this scenario, using async/await does not provide any advantage.
The code could be written like this:
let fetchKanji = name => fetch(`http://localhost:8080/public_html/static/kanjiSVG/${name}.svg`, {method: "GET"})
.then(response => response.text())
.then(svgRawText => svgRawText.replace(/[\s\S]*(?=<svg)/,""));
function addAllKanji() {
let fileNames = ["0f9a8","064e3","05ae1","05afa","062ac","062c8"];
return Promise.all(fileNames.map(fetchKanji));
}
addAllKanji().then(allSVGElements => {
console.log("length: "+allSVGElements.length);
console.log(allSVGElements);
console.log("length: "+allSVGElements.length);
allSVGElements.forEach(ele => {
console.log(ele);
console.log("running forEach")
});
});
No async/await used here :p
Although some people find the following syntax easier to read:
let fetchKanji = async (name) => {
const response = await fetch(`http://localhost:8080/public_html/static/kanjiSVG/${name}.svg`, {method: "GET"});
const svgRawText = await response.text();
return svgRawText.replace(/[\s\S]*(?=<svg)/,"");
};
Feel free to choose the style that works best for you!