Blob video stream not showing on iOS when receiving a stream from socket.io (JavaScript and Node.js)

This works perfectly fine on android (every part of it). But when I receive a video stream wrapped in a blob on iOS from android or another iOS device, it does not show any sign of loading the video or displaying it. However, when I show my own video to myself on iOS, it works.

I have tried the following:

video.setAttribute('autoplay', '');
video.setAttribute('playsinline', '');
video.setAttribute('muted', '');

Or adding a source element to the video element, but these did not work.

How am I supposed to fix the receiving video issue on iOS?

Code (sorry for all the styling):

Client:

let media;
const done = document.getElementById('done');
const vidCon = document.getElementById('video-con');
var getUserMedia = (navigator.mediaDevices.getUserMedia || navigator.mediaDevices.webkitGetUserMedia || navigator.mediaDevices.mozGetUserMedia).bind(navigator.mediaDevices);
    getUserMedia({
        video: true,
        audio: true
    }).then((stream) => {
        const myVideo = document.createElement('video');
        myVideo.srcObject = stream;
        myVideo. setAttribute('autoplay', '');
        myVideo. setAttribute('muted', '');
        myVideo. setAttribute('playsinline', '');
        myVideo.style.width = '100%';
        myVideo.style.height = '80%';
        myVideo.muted = true;
        myVideo.style.display = 'block';
        myVideo.style.objectFit = 'cover';
        media = new MediaRecorder(stream); 
        media.onstart = function(e) {
        this.chunks = [];
        myVideo.play();
        document.getElementById('video-base-con').append(myVideo);
    }
    done.onclick = function() {
        media.stop();
        audio.src = "93642-Blakes_7_Gun_144bpm.wav";
        audio.play();
        audio.addEventListener('ended', go);
        done.style.display = 'none';
        document.getElementById('blank-choosing').style.display = 'block';
    }
    media.ondataavailable = function(e) {
        this.chunks.push(e.data);
    }
    media.onstop = function(e) {
        myVideo.remove();
        var blob = new Blob(this.chunks, { 'type' : 'video/ogg; codecs=opus' });
        socket.emit('send-video', blob);
    }
});
socket.on('recieve-video', (stream, codeNew) => {
            if (codeNew == code.value) {
                document.getElementById('blank-video').style.display = 'none';
                console.log('recieved video.');
            const blob = new Blob([stream], { 'type' : 'video/ogg; codecs=opus' });
            const video = document.createElement('video');
            video.src = window.URL.createObjectURL(blob);
                                video. setAttribute('autoplay', '');
video. setAttribute('muted', '');
video. setAttribute('playsinline', '');
            vidCon.style.display = 'block';
            video.style.width = '90%';
            video.style.height = '100%';
            video.style.objectFit = 'cover';
            vidCon.style.width = '100%';
            vidCon.style.height = '100%';
            vidCon.style.textAlign = 'center';
            vidCon.style.backgroundColor = 'lightgray';
            vidCon.style.borderRadius = '30px';
            vidCon.append(video);
            video.play();
            video.addEventListener('ended', () => {
                video.remove();
                vidCon.style.display = 'none';
                answers.style.display = 'block';
            }, false);
            }
        });

Server:

socket.on('send-video', (blob) => {
     socket.broadcast.emit('recieve-video', blob, code); 
});

Thanks in advance!

Reactjs creates infinite loop using setTimeout

Here is my App.js that contains beside Header and the MainView
an AlertDialog. Alert dialog has two state controlled props:

msg={alertMsg} toggleClass={alertToggleClass}

The task of AlertDialog is to show if the className is “alertDlg” and disappear if it’s “alertDlg alertDlgClosed”. Testing it via the inspector manually (changing className) shows, that it works fine.

Therefore alertToggleClass is set to “alertDlg alertDlgClosed” when initializing, so that the alert dialog is hided by default.

Within the MainView Component (before render())
sendGlobalAlert("Test Alert Msg") gets called which is simply a callback to the showAlert(msg) method in App.js.

Now here goes the tricky part: calling setAlertToggleClass("alertDlg"); in showAlert(msg)-method shows the custom alert dialog as expected. However trying to disable it by calling setAlertToggleClass("alertDlg alertDlgClosed"); within the setTimeout creates an infinite loop to showAlert(msg)-method.

As far as I can see, there is no recursivity is in setTimeout(...).

I can’t explain this behavior and would appreciate any helpful hints.

import './App.css';
import AlertDialog from './components/general/alert-dialog/AlertDialog';
import { Header } from './components/general/Header';
import MainView from './components/main/MainView';
import { useState } from "react";

function App() {
    const [alertMsg,setAlertMsg] = useState(""); 
    const [alertToggleClass,setAlertToggleClass] = useState("alertDlg alertDlgClosed"); 

    function showAlert(msg){
        console.log("Showing alert dialog");
        setAlertMsg(msg); // set message
        setAlertToggleClass("alertDlg"); // show alert dialog
        
        setTimeout(function() {
            if(alertToggleClass === "alertDlg" ){
                setAlertToggleClass("alertDlg alertDlgClosed");
                console.log("hide alert");
            }
            // setAlertToggleClass("alertDlg test");
        },3500);
    }
    return (
        <div className="container">
            <Header/>
            <MainView sendGlobalAlert={showAlert}/>
            <AlertDialog msg={alertMsg} toggleClass={alertToggleClass} />
        </div>
    );
}

export default App;

Failed to POST: Post “http://localhost:3000/webhook”: context deadline exceeded (Client.Timeout exceeded while awaiting headers)

I have this error when I run stripe listen --forward-to localhost:3000/webhook on cmd and server on hyperterminal.
[stripe listen –forward-to localhost:3000/webhook][1]

I basically copied and pasted from the document so I’m not sure what is the problem
[1]: https://i.stack.imgur.com/iosZa.png
[2]: https://i.stack.imgur.com/Wk0xY.png

const stripe = require("stripe")(process.env.STRIPE_PRIVATE_KEY);
const bodyParser = require("body-parser");
const app = express();

app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
  const payload = request.body;

  console.log("Got payload: " + payload);

  response.status(200);
});

Add class to an input when its focused, and remove it when isnt focused

I’m trying to add the class “.contact__form-input–focused” to the input that is focused from a form.

I’m trying to do that adding an event listener to every input, and then if it has the class already delete that class from the classlist.

//INPUT ANIMATION
const input = document.querySelectorAll("contact__form-input");

function addClass(input) {
  input.classList.add("contact__form-input--focused");
}

function removeClass(input) {
  input.classList.remove("contact__form-input--focused");
}

for (let i = 0; i < input.length; i++) {
  if (item[i].classList.contains("contact__form-input--focused")) {
    item.addEventListener("focus", addClass(input[i]));
  } else {
    item.addEventListener("blur", removeClass(input[i]));
  }
}
.contact__form {
  display: flex;
  flex-direction: column;
}

.contact__form-input {
  border: none;
  border-bottom: .1rem solid rgba(0, 0, 0, .12);
  font-size: var(--medium-font-size);
  margin: 0;
  padding: 4px 0;
  width: 100%;
  background: 0 0;
  text-align: left;
  color: inherit;
}

.contact__form-input--focused {
  /*some animations here*/
}
<form class="contact__form" method="POST">
  <label class="contact__form-label">
            <span>Name</span>
            <input class="contact__form-input" name="Name" type="text" autocomplete="name" required>
          </label>
  <label class="contact__form-label">
            <span>Phone number</span>
            <input class="contact__form-input" name="Phone number" type="tel" autocomplete="tel" required>
          </label>
  <label class="contact__form-label">
            <span>Message</span>
            <input class="contact__form-input" type="text" required>
          </label>
  <button class="contact__form-button">Send</button>
</form>

ReactJS Update child component after API call returns

So I have a simple reactJS app that contains a app.js with a HomePage.js

The HomePage.js need to display some data for me that I fetch trough an await API.get method from amplify. ( : https://docs.amplify.aws/lib/restapi/fetch/q/platform/js/ )
The API.get method triggers the .then response and then gives me exactly the correct array with item that I want.

Now I want to render those items on my HomePage.js, which is a functional component.

My app.js looks like this (ignore the token stuff, this is another problem i need to solve) :

import React, { useState } from "react";
import logo from './logo.svg';
import './App.css';
import Amplify, { API, Auth } from 'aws-amplify';
import { withAuthenticator , Link } from "@aws-amplify/ui-react";
import '@aws-amplify/ui-react/styles.css';
import { Button } from '@aws-amplify/ui-react';
import Appbar from "../src/components/Appbar/Appbar";
import Homepage from './components/Homepage/Homepage';

// let user;
let user = {}; 
let userName = "placeholder";
// let pageLoaded = false;
let passArray;
let zorgSearchData;

function App() {

  callApi();
  async function callApi() {
    user = await Auth.currentAuthenticatedUser()
    const token = user.signInUserSession.idToken.jwtToken
    userName = user.username;
    const requestData = {
      headers: {
        Authorization: token
      }
    }


    zorgSearchData = await API
    .get('caresyncapi' , '/items/zorgsearch/' + userName)
    .then(response => {
      console.log("resp!")
      console.log(response);
      passArray = response;
    })
  }

  return (
      <div className="App">
        <Appbar/>
        {<Homepage passedArray={passArray} />}

    </div>
    );  
  }


export default withAuthenticator(App);

The API.get calls and the .then prints out the exact response I want. I pass passArray as a prop to HomePage.js which (i think and am probably wrong) should update with the new data. The problem is when the .then is called there is no change in the Homepage.js . The props I retrieve in Homepage.js is always undefined. I think this is because the API is async and retrieves the prop after I pass it for the first time. But how do I update this? Anyway, my Homepage.js looks like this:

import React, { useState } from 'react';
import "./homepage.css";
import { makeStyles } from '@material-ui/core/styles';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import { Typography } from '@material-ui/core';

const useStyles = makeStyles((theme) => ({
    formControl: {
      margin: theme.spacing(1),
      minWidth: 120,
    },
    selectEmpty: {
      marginTop: theme.spacing(2),
    },
  }));

const Homepage = ({props}) =>{
    const classes = useStyles();
    const [age, setAge] = useState(''); 
    console.log(props);


    function handleChange (event) {
        console.log(event.target.value); 
        // console.log({passedData})
        //setAge(event.target.value);
    };

    return (
        <>
            <Typography variant="h1">{`Welcome,username`}</Typography>
                <FormControl variant="outlined" className={classes.formControl}>
                    <InputLabel id="demo-simple-select-outlined-label">Age</InputLabel>
                    <Select
                    labelId="demo-simple-select-outlined-label"
                    id="demo-simple-select-outlined"
                    value={age}
                    onChange={handleChange}
                    label="Patienten"
                    >
                        {/* {this.state.searchData.map(x=> <MenuItem >{x.PatientNaam}</MenuItem>)} */}
                        <MenuItem value="">
                            <em>None</em>
                        </MenuItem>
                        <MenuItem value={10}>Ten</MenuItem>
                        <MenuItem value={20}>Twenty</MenuItem>
                        <MenuItem value={30}>Thirty</MenuItem>
                    </Select>
                </FormControl>
            <div className="homepage-container">
                <div className="homepage-text-container">
                    <h1 className="welcome-message">Hello, {props}</h1>
                    <p>lorem ipsum</p>
                </div>
                <div className="chart-container">
                    <div className="chart-1">
                        <h3>Chart 1</h3>
                        <div className="chart"></div>
                        <p>More text....</p>
                        <p></p>
                    </div>
                </div>
            </div>
        </>
    )
}



export default Homepage

As you can see I am also trying to fill the select form with my array names, but I think I can figure that out as long as I have a valid array. I tried different methods of the handleChange and passing props, but nothing seems to work.

TL;DR : I have a app.js which calls an async get function, this returns a valid object I use. The problem is I pass this object array to Homepage.js ( {} ) before the async method returns a value. So the array is always undefined in Homepage.js

Can someone point me in the right way? Do I need to force a change? Is there a way to pass the prop again? Is there something I can do in the handleChange method? I can access the .then method, do I need to do something from there? Simply updating the variable doesn’t seem enough.

Thanks in advance! Sorry for the ramble im new to reactJS and I am trying to solve this problem after a few beers.

Why quick sort is always slower than bubble sort in my case?

They use same array:

QUICK SORT Time: 3159 miliseconds (array length 10K)

Bubble SORT Time: 1373 miliseconds (array length 10K)

I’m trying to compare time of the sorting using quick and bubble sort algoritms. I use the array with 10K different random numbers sorted in random order for both functions. But for some reason bubble sort is always sort array faster than quick sort, even if average time complexity of bubble sort is worse than average time complexity of quick sort. Why bubble sort algorithms slower than quick sort algorithm in my case? (I tried different lengths of array, from 10 to 10K)

Thats my quick sort function

let quickSort = (arr) => {
    if (arr.length <= 1) {
        return arr
    }
    const pivot = arr[0]
    const rest = arr.slice(1);
    let left = [],
        right = [];
    rest.forEach(el => el > pivot ? right = [...right, el] : left = [...left, el]);
    return [...quickSort(left), pivot, ...quickSort(right)];
}

And that’s my bubble sort function

let bubbleSort = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        for (let s = i + 1; s < arr.length; s++) {
            if (arr[s] < arr[i]) {
                let a = arr[i];
                arr[i] = arr[s]
                arr[s] = a;
            }       
        }
    }
    return arr
}

add an active class to one of my elements and select only the relevant parent

In my menu I would like to add an active class to one of my elements: li.nav-item
and this only if the child item: ul.nav-collapse.li has the active class.

for this I made a script that works but it adds the active class to all elements: li.nav-intem

I would like it to select only the relevant parent: li.nav-item
which contains the active class ul.nav-collapse.li.active

JS

$('ul.nav-collapse li').each(function(){
    if($(this).hasClass('active')) {
        $(this).parent().parent().parent().parent().find('li.nav-item').addClass("active");
    }
});



HTML

<ul>
    <li class="nav-item">
        <a class="" data-toggle="collapse" href="#submenu1">
            <p>My Folder</p>
        </a>
        <div class="collapse" id="submenu1">
            <ul class="nav nav-collapse">
                <li class="">
                    <a href="SubFolder">
                        <span class="sub-item">SubFolder</span>
                    </a>
                </li>
                <li class="active">
                    <a href="SubFolder2">
                        <span class="sub-item">SubFolder2</span>
                    </a>
                </li>
            </ul>
        </div>
    </li>
    <li class="nav-item">
        <a class="" data-toggle="collapse" href="#submenu2">
            <p>My Folder2</p>
        </a>
        <div class="collapse" id="submenu2">
            <ul class="nav nav-collapse">
                <li class="">
                    <a href="SubFolder2">
                        <span class="sub-item">SubFolder2</span>
                    </a>
                </li>
                <li class="">
                    <a href="SubFolder2_2">
                        <span class="sub-item">SubFolder2_2</span>
                    </a>
                </li>
            </ul>
        </div>
    </li>
    <li class="nav-item">
        <a class="" data-toggle="collapse" href="#submenu3">
            <p>My Folder2</p>
        </a>
        <div class="collapse" id="submenu3">
            <ul class="nav nav-collapse">
                <li class="">
                    <a href="SubFolder3">
                        <span class="sub-item">SubFolder3</span>
                    </a>
                </li>
                <li class="">
                    <a href="SubFolder3_2">
                        <span class="sub-item">SubFolder3_2</span>
                    </a>
                </li>
            </ul>
        </div>
    </li>
</ul>

I would like something like this

<ul>
    <li class="nav-item active">
        <a class="" data-toggle="collapse" href="#submenu1">
            <p>My Folder</p>
        </a>
        <div class="collapse" id="submenu1">
            <ul class="nav nav-collapse">
                <li class="">
                    <a href="SubFolder">
                        <span class="sub-item">SubFolder</span>
                    </a>
                </li>
                <li class="active">
                    <a href="SubFolder2">
                        <span class="sub-item">SubFolder2</span>
                    </a>
                </li>
            </ul>
        </div>
    </li>
    <li class="nav-item">
        <a class="" data-toggle="collapse" href="#submenu2">
            <p>My Folder2</p>
        </a>
        <div class="collapse" id="submenu2">
            <ul class="nav nav-collapse">
                <li class="">
                    <a href="SubFolder2">
                        <span class="sub-item">SubFolder2</span>
                    </a>
                </li>
                <li class="">
                    <a href="SubFolder2_2">
                        <span class="sub-item">SubFolder2_2</span>
                    </a>
                </li>
            </ul>
        </div>
    </li>
    <li class="nav-item">
        <a class="" data-toggle="collapse" href="#submenu3">
            <p>My Folder2</p>
        </a>
        <div class="collapse" id="submenu3">
            <ul class="nav nav-collapse">
                <li class="">
                    <a href="SubFolder3">
                        <span class="sub-item">SubFolder3</span>
                    </a>
                </li>
                <li class="">
                    <a href="SubFolder3_2">
                        <span class="sub-item">SubFolder3_2</span>
                    </a>
                </li>
            </ul>
        </div>
    </li>
</ul>

any idea?

how to close the sidebar when clicking outside?

I’m a noobie at programing. I’m currently making a simple shop website for a project in class. I’m currently struggling with how to make it work.

This is my complete style sheet

     <style>
        .open{
            cursor: pointer;
            background-color: black;
            text-align: center;
            padding: 5px;
            font-size: 40px; 
        }
        
        .open i {
            color: white;
            height: 50px;
            width: 50px;
        }
        
        #Sidenav {
            height: 100%;
            width: 0px; 
            position: fixed;
            z-index: 1; 
            top: 0; 
            left: 0; 
            background-color: black;
            overflow-x: hidden; 
            transition: 0.5s; 
        }
        
        .logo {
            margin: 20px 0 0 0; /* top right down left */
            width: 75%;
            padding-bottom: 10px;
            border-bottom: 1px solid white;
        }
        
        .logo img {
            margin: 0;
            height: 100px;
            width: 100px;
            
        }
        
        .sidenav ul {
            margin: 0 0 0 12.5%;/* top right down left */
            padding: 0;
            width: 75%;
            list-style: none;
        }
          
        .sidenav ul li a {
            text-decoration: none;
            color: black;
            position: relative;
        }
        
        .sidenav ul li{
            margin: 10px 0 10px 0; /* top right down left */
            background-color: white;
            border-radius: 20px;
            text-align: center;
            line-height: 30px;
            font-size: 20px;
        }
    </style>

All of HTML codes are working fine

<body>
    <span class="open" onclick="OpenNav()"><i class="fas fa-bars"></i></span>/* My button */

    <nav id="Sidenav" class="sidenav">
            
            <center>
                <div class="logo">   
                    <<img src="#" alt="logo"/>
                <div>
            </center>
            
            <ul>
                <li><a href="#">All Items</a></li>
                <li><a href="#">Smartphones</a></li>
                <li><a href="#">Appliances</a></li>
                <li><a href="#">PC Components</a></li>
                <li><a href="#">Software</a></li>
                
                <li><a href="#">My Cart</a></li>
                <li><a href="#">Account</a></li>
                <li><a href="#">Shop Inventory</a></li>
                <li><a href="#">Login</a></li>
            </ul>
        </nav>
    
    <h1>Content
    <div id="main">
        
    </div>

The function OpenNav() work fine as well, but when I put the Closenav function I can’t click on anything else.

    <script>
        function OpenNav() {
          document.getElementById("Sidenav").style.width = "250px";
        }

        document.onclick = function(Closenav){
           if(Closenav.target.id !== 'Sidenav'){
              document.getElementById("Sidenav").style.width = "0px";
           };
        };
    </script>
</body>

Await is only valid in async functions and the top level bodies of modules? [duplicate]

I am running a migration script in sequelize:

    let sort = 10;

return await queryInterface.sequelize.transaction(async (transaction) => {
  await Promise.all(
    sortedHolidays.map((holidayName) => {
      sort += 10;
      await Model.Holiday.update({ sort }, { where: { holidayName }, transaction });
    })
  );
});

I defined all my functions async, and awaiting all the functions, why am i getting this error of :
Await is only valid in async functions and the top level bodies of modules?

Rock Paper Scissors Prompt To Ask for Decision to run the game

Hello StackOverflow Community,

I have been studying JavaScript for about 3 days give or take and I have created a rock paper scissor “game” that runs but only with the player decision is added to the code. I wanted to fix this instead so that an prompt alert pops up to ask “Pick Rock, Paper, Scissor Now” and have the game use that input as the deciding factor to who will win. I have ran the code that I have provided and ended up this error:

 a internal/modules/cjs/loader.js:638
    throw err;
    ^

Error: Cannot find module 'readline-sync'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/tmp/zUokdwLcHz.js:1:20)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3) 

I tried reviewing my spelling and ()/;/, to make sure that they are all correct and I feel like they are. I am sure this is an easy fix so thank you in advance you if you can guide me the correct way.

Here is the code:

const userInput = prompt("What will you shoot")
userInput = userInput.toLowerCase();
if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
  return userInput;

} else {
  console.log("Error!");
}

const ComputerChoice = () => {
  const randomNumber = Math.floor(Math.random() * 3)
  if (randomNumber === 0) {
    return "rock";
  } else if (randomNumber === 1) {
    return "paper";
  } else {
    return "scissors";
  }
}

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice) {
    return "Tie, please try again";
  } else if (userChoice === "paper" && computerChoice === "rock") {
    return "Player wins";
  } else if (userChoice === "scissors" && computerChoice === "Paper") {
    return "Player wins";
  } else if (userChoice === "rock" && computerChoice === "scissors") {
    return "Player wins";
  } else if (userChoice === "bomb") {
    return "Player wins"
  } else {
    return "Computer Wins"
  }
}

const playGame = () => {
  const userChoice = getUserChoice('')
  const computerChoice = ComputerChoice()
  console.log("you threw a " + userChoice);
  console.log("The computer threw a " + computerChoice);

  console.log(determineWinner(userChoice, computerChoice));
}

playGame();

save and update twitch followings. Javascript

I would like the usernames from user x, which are followed by person x. if I use my function “secondFunction ()” then it adds each new person individually in square brackets. I’m slowly becoming desperate, I want to use the function to add users manually, update followers and remove duplicates. So far it has always overwritten the existing users for me. I was now at the point where they are added and not overwritten. I hope and ask for your help 🙂
I once uploaded the code to jsfiddle so as not to make it too crowded ^^

https://jsfiddle.net/jwqh46xy/

my “con.json” looks like this:

user 5, 6 & 7 would be the ones that were newly added

{
  "applicationid": "123456",
  "token": "123456",
  "access_token": "123456",
  "twitch": {
    "userX": [
      "user1",
      "user2",
      "user3",
      [
        "user5"
      ],
      [
        "user6"
      ],
      [
        "user7"
      ]
    ],
    "user1": [
      "user1",
      "user2",
      "user3",
      [
        "user5"
      ],
      [
        "user6"
      ],
      [
        "user7"
      ]
    ],
    "otherData": {
      "Anything": "value",
      ...
    },
    ...
  }
}

Many thanks in advance

Can anyone explain to me why escaping numbers n Regular Expressions causes an error

I am writing some code for someone and wanted to show them different ways they could count the no of times a character/no occur in a longer string using both IEnumerable and RegEx however I have found that when I am trying to count the no of times a number occurs in a string none of my methods work despite me converting the no into a literal character first. However trying to use a variable and the cast methods does not work e.g:

char chr = '2'; // works fine

So this literal works however all the other ways which I need to be able to use on variables such as converting an int variable into a char with either (char)no or Convert.ToChar(no) doesn’t work for some reason.

I am sure there is a simple reason but I cannot seem to crack it.

This is my code, the reason there are two methods using RegEx is that I was testing the best way to count special characters such as dots . in a string with C#.

I didn’t know whether it was best to just RegEx.Escape any variable being passed in to my count method or whether I needed to check first whether it needed to be escaped before doing so or just leaving the character alone.

The code calling the test functions is below, the reason I am using a static class to log out the errors is I am just adding this method into a bigger project to do the test quickly and all the HelperLib class is used for is logging with adding a date stamp next to each line, debugging, setting up system wide settings on load and so on…

private void TestCode()
{
    this.HelperLib.LogMsg("IN TestCode - Run Tests on numbers");

    string word = "22.2.34.3";
    int no = 2;
    // char chr = (char)(no); // converting a variable which I need to do doesn't work
    char chr = Convert.ToChar(no) // doesn't work
    // char chr = '2'; // when we do it as a literal it works

    // correct amount of 2 (as a char) in the string should be 3 but we get 0 for each attempt
    int a = word.CountChars(chr);
    HelperLib.LogMsg("Use IEnumerable.Count; There are " + a.ToString() + " occurrences of " + chr.ToString() + " in " + word);

    int b = word.CountChars2(chr);
    HelperLib.LogMsg("RegEx.Escape all chars; There are " + b.ToString() + " occurrences of " + chr.ToString() + " in " + word);

    int c = word.CountChars3(chr);
    HelperLib.LogMsg("Test for special char first before escaping; There are " + c.ToString() + " occurrences of " + chr.ToString() + " in " + word,);

    return;
}

And the methods I am using are in an Extensions class so I can just add them to strings.

public static int CountChars(this string value, char letter)
{
    int count = value.Count(ch => ch == letter);
    return count;
}

public static int CountChars2(this string value, char letter)
{
     // if the letter is a special char then escape it otherwise leave it alone
     string re = (letter.IsSpecialChar()) ? Regex.Escape(letter.ToString()) : letter.ToString();                           
     int c = Regex.Matches(value, re, RegexOptions.IgnoreCase).Count;
     return c;
 }

public static int CountChars3(this string value, char letter)
{
    // escape all characters passed in, in case its a special character               
    string re = Regex.Escape(letter.ToString());
    int c = Regex.Matches(value, re, RegexOptions.IgnoreCase).Count;
    return c;
}

// test to see if we need to escape a character that is a special character in RegEx
public static bool IsSpecialChar(this char letter)
{
    char[] x = { '.', '\', '+', '*', '?', '[', ']', '$', '(', ')', '{', '}', '=', '!', '<', '>', '|', ':', ':', '-', '#' };
    bool ret = (x.Contains(letter)) ? true : false;
    return ret;
}

And the debug I get back is below…

10/12/2021 23:11:28 - IN TestCode - Run Tests on numbers;
10/12/2021 23:11:28 - Use IEnumerable.Count; There are 0 occurrences of 2 in 22.2.34.3;
10/12/2021 23:11:28 - RegEx.Escape all chars; There are 0 occurrences of 2 in 22.2.34.3;
10/12/2021 23:11:28 - Test for special char first before escaping; There are 0 occurrences of 2 in 22.2.34.3;

So I can count letters including special characters used in RegEx like dots without a problem but when it comes to numbers even converting them to a character first doesn’t seem to work and I am stuck to why this is occurring as a literal ‘2’ works but a variable converted to a Char doesn’t.

Also when using JavaScript, as I have a test page for testing expressions before using them in whatever language I need, I have found that escaping every character doesn’t work when it comes to numbers OR special characters for example with the same string “22.2.34.3” when I try 2 it return 0 matches but just 2 returns 3 with this code:

// returns 0
var value = "22.2.34.3";
re = "2"; // tried with double \ and triple \
var exp = new RegExp(re,"gi");
var no = value.match(exp)||[];
alert("NO OF MATCHES " + no.length);

// returns 3
var value = "22.2.34.3";
re = "2";
var exp = new RegExp(re,"gi");
var no = value.match(exp)||[];
alert("NO OF MATCHES " + no.length);

What does a single escaping backslash next to a digit mean to the RegEx machine as it works with letters except special RegEx characters like d or w however I thought by escaping those characters it would mean they would be treated like literals not special characters (digit, word char) etc?

Therefore in JavaScript what would I need to do to count the number of a single no in a longer number e.g “2” in “22.2.34.3” OR count the number of character “d” in a string like “does it matter don’t do it” as a single escape string doesn’t work with the code I am using shown above (or a double/triple backslash)??

Any help in understanding this would be appreciated. Thanks.

How to get Async code to actually wait for the function to finish executing before continuing [duplicate]

What I’m trying to do

I’m still new to working with asynchronous code, I’m trying to do something basic, but I’m not seeing what’s missing here.

So I have this function that gets all orders from Firestore.

getAllOrders() = async () => {
    var orderArray = []

    this.firestore.collection('orders')
      .where('status', '==', status) 
      .where('createdAt', '>=', start)
      .where('createdAt', '<=', end)
      .get()  
      .then(snapshot => {              
        snapshot.forEach(docs => {
            orderArray.push(docs.data())
        })
        console.log(orderArray); //outputs the orders correctly
        return orderArray;
       }).catch(error => {
        console.log(error)
       })
}

I want to call getAllOrders to get the orders and output them to the console. I tried the 2 following methods to get the orders to print. Both output undefined.

Method 1

const onSubmit = async () => {
    props.firebase.getAllOrders().then((orders) => {
        console.log(orders);
    })
}

Method 2

const onSubmit = async () => {
    const orders = await props.firebase.getAllOrders()
    console.log(orders)

}

The first thing that is outputted is undefined and then the correct order array, so the await is not working. I know I’m missing something to get this to work. What should I change it to make it work?