JavaScript is incorrectly showing the array as empty despite containing strings

I am experiencing an issue with my array of strings in JavaScript. Despite having strings in the array when I print it in the console, the forEach function runs 0 times and JS claims the array is empty when I print its size. What could be causing this?https://i.sstatic.net/2s44T.png

import {drawKanji} from "../KanjiDrawing/kanji-painter-original";

require('../../css/kanji.css');

window.onload = addAllKanji;

var allSVGElements = [];

async function addAllKanji(){
    let fileNames = ["0f9a8","064e3","05ae1","05afa","062ac","062c8"];
    await fileNames.forEach(function (fileName) {
       fetchKanji(fileName);
    });
    addKanjiToHTML();
    drawKanji();
}

function fetchKanji(name){
    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);
}

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")
    });
}

Answer №1

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!

Answer №2

This is my concept.

let and await are exclusive to being used within an async function. They will not function properly in global functions, resulting in a lack of access to global functions such as "fetchKanji(name)". Adjust your code accordingly and see the difference.

Answer №3

When you execute the following code, everything runs smoothly.

let fileNames = ["0f9a8","064e3","05ae1","05afa","062ac","062c8"];
    await fileNames.forEach(function (fileName) {
       console.log(fileName);
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is AngularJS redirection not retrieving the value from window.localStorage?

After utilizing local storage, I encountered an issue where upon logging in and being redirected to the myprofile page, the local storage value was not loading properly. Instead, I was getting a null value. It wasn't until I manually reloaded the page ...

Node is throwing a 302 error on Localhost:3000

Looking for some guidance as a beginner trying to create and run a nodejs application. Encountering an error while running server.js via nodemon, the console displays the following: Express server listening on port 3000 Mongoose default connection open t ...

Showing the image as a backdrop while scrolling through text

How can I create an effect that continuously displays the image while scrolling text in Internet Explorer without using position: sticky or position: fixed? var sticky = document.querySelector('.sticky-container'); var img = document.querySele ...

Trigger a function following a collection update in Angular Meteor

I am in the process of developing a multiplayer game, and I would like a specific function to be triggered once the first player updates an "isStarted" field in the collection. Within my controller code: angular.module('mcitygame').directive(&a ...

Misconception about the usage of jQuery's .each() function clarified with an illustrative example

Problem Description (See Fiddle): When clicking on the red boxes, they transform into kittens and display an alert with the current value of i. Clicking on a large fading kitten will reset everything. I am puzzled as to why alert(i) is triggering multipl ...

The element's position remains unchanged after the .click re-event in the function

Welcome to my first attempt at using jQuery! Please bear with me as I navigate through this learning process. Here's the challenge: I have a series of elements in my HTML. <div class="garden"> <div class="point left">&#9668;</d ...

My content is being obstructed by a single-page navigation system

I attempted to create a simplified version of the issue I am facing. Basically, I am working on a header with navigation that stays at the top of the page while scrolling. The problem arises when clicking on a section in the navigation. The screen scrolls ...

Filling out a form within a webpage fetched through a DOMParser

Creating automation software in JavaScript using TamperMonkey. The script performs several AJAX requests that retrieve HTML to be parsed with a DOMParser. Is there a way to submit these forms without opening the newly retrieved HTML on the main page? ...

Switch out the arrow icon in the dropdown menu with an SVG graphic

Looking for a way to customize the dropdown caret in a semantic-ui-react component? Here's how it currently appears: https://i.sstatic.net/GpvfC.png <Dropdown className="hello-dropdown" placeholder="Comapany" onChange={th ...

Tips for Running a Unique Code the First Time the $.each() Function is Used

During the initial iteration of my $.each() loop, I run a unique code. However, for all subsequent iterations until the end of the loop, my code remains the same. ...

Ways to create distinct identifiers within a recurring function:

I am using this function twice: function (data) { $.each(data.items, function(i,item) { var $items = $('<div class="col-sm-4 grid-item"><div class="thumbnail"><input type="checkbox" name="thing_'+i+'" ...

What is the best way to use ajax to send a specific input value to a database from a pool of multiple input values

Welcome everyone! I'm diving into the world of creating a simple inventory ordering site, but am facing a roadblock with a particular issue: Imagine you have a certain number (n) of items in your inventory. Based on this number, I want to run a &apos ...

Breaking down a number using JavaScript

Similar Question: JavaScript Method for Separating Thousands I'm looking to find a way to separate numbers by a thousand using JavaScript. For example, I would like to turn "1243234" into "1 243 234", or "1000" into "1 000" and so on. (sorry for ...

Include a Vue component within another Vue component in a Laravel application using VueJs

I've recently integrated Vue.js into my Laravel project and encountered an issue when trying to call a component within another component. After running the command npm run dev, I received a webpack error. Here is the code snippet from my parent comp ...

Implementing AJAX in Rails for the new/create action can greatly enhance the user

I have a timeline with event sections on it that allow you to create, view, update, and delete events directly on the timeline page. Currently, the functionality for deleting an event is working smoothly as the delete section refreshes along with the timel ...

Swapping out the video in real-time using an on-demand script

Recently, I encountered an issue with my blog's YouTube video switcher. It seems that the videos won't play once they are changed, and it is related to a light YouTube embed script that I found here: . I believe this script was implemented to imp ...

Switching between play and pause for the video element using a component for the child

Trying to toggle the play/pause of a child video by clicking on a parent div can be challenging, especially when dealing with multiple instances of the same div and video. A normal function may only work for one specific video, as mentioned by @ken. I hav ...

Incorporating an NPM module with dependencies within the Meteor framework

I'm encountering some difficulties while attempting to integrate an NPM package into my meteor project. The specific module I am trying to utilize is the steam package. In order to make this work, I have included the meteorhacks:npm package for mete ...

Clipped Words & Silhouettes

I'm having trouble ensuring the text in this particular example displays correctly. I am experiencing challenges with the clipping of text and shadows on certain letters, and I'm struggling to identify the root cause as well as the solution. In ...

Utilizing jQuery to Sort Table Rows based on an Array of Class Names

I have a table containing values and a filter option where users can select multiple values to filter the table. I want to create a filter with numbers ranging from 1 to 10, and assign class names like filter_1, filter_2, filter_3, etc. to each table row ( ...