Javascript – forEach with promise.all not working

I tried to handle promises with for each but not working

I assume it will log something because of console.log(result).

Why is it not working?

It only logs

All done (54) [ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ, ƒ]
          let promises = [];
                  mkt.forEach(async function (marketItem, index) {
                    promises.push(() => {
                      context.program.account.chain
                        .fetch(sth)
                        .then((result) => {
                console.log(result)
                        });
                    });
                  });
          Promise.all(promises)
                    .then(results => {
                      console.log('All done', results);
                    })
                    .catch(e => {
                      // Handle errors here
                    });

How to close popup and redirect to parent window?

Let there be three windows.

GrandParent->parent->child.

GrandParent opens parent and parent opens child.

In our case child closes automatically and returns to parent. but when parent is closed it doesn’t return to GrandParent instead it goes to another tab.

I already tried the solution of creating a function in grandparent and calling it in parent. But it doesn’t work.

Using prevState Callback function in UseState react Hook

I have some array of products inside filteredProducts variable and wanted to sort them according to the price and newly added products.
When using prevState like this without having { } in the callback function, the code runs fine.

useEffect(() => {
    if(sort === "newest") {
        setFilteredProducts((prevState) => 
            [...prevState].sort((a, b) => a.createdAt - b.createdAt)
        );
    }
    else if (sort === "asc") {
        setFilteredProducts((prevState) => 
            [...prevState].sort((a ,b) => a.price - b.price)
        );
    }
    else {
        setFilteredProducts((prevState) => 
            [...prevState].sort((a, b) => b.price - a.price)
        );
    }
}, [sort]);

But when using { } for the prevState callback function like this

if(sort === "newest") {
        setFilteredProducts((prevState) => {
            [...prevState].sort((a, b) => a.createdAt - b.createdAt)
        });
    }

, it is just throwing error in console.

want to time the images for animation in p5.js?

In p5.js i am creating an animation using images .how can i time frame the images such that after clicking on thee button they must execute the code. i want to execute a code where after clicking the button the images must move towards the p5.png.here i have used 6 images for simulation .how could i animate those images such that after clicking the button they must run or execute the code.

var pic1;
var pic2;
var pic3;
var pic4;
var pic5;
var pic6;
let button;
let posX=0
let posY=0

const rightwall=350;
const height=450;
function preload(){
  pic1=loadImage("5.png")
  pic2=loadImage("Iron ore.jpg")
  pic4=loadImage("blastfurnace.jpg")
  pic5=loadImage("coal2.jpg")
  pic6=loadImage("limestone.jpg")
  pic3=loadImage("slag.jpg")
  
  
}
function setup(){
  createCanvas(600,600);
  background("blue");
  button=createButton("CLICK TO LOAD INTO FURNACE") 
  button.position(150,330);
  button.mousePressed(changeBG);
  
  noLoop();
}
function changeBG() {
  let val = random(65);
  background(val);
  loop();
  playAnim=true;
  draw();
  posX=0;
  posY=0;
  // background will be overwritten with 220
}

function draw() {
  background(220);
 // text(mouseX + "," + mouseY, 20, 20);
  // If the 'a' key is pressed, draw the following text in the canvas
if (key === 'a'){
  textSize(22);
  text('a key was pressed!', width / 2, height / 2);
}
  let s='BLAST FURNACE';
textSize(32);
fill(0,102,153);
 text(s,50, 10,300, 400);
 
  img1=image(pic1, 320, 30, 170,210)
  img2=image(pic2, posX, 70, 70, 70)
  img4=image(pic4,100,350,250,250)
  img5=image(pic5,posX,10,50,50)
  img6=image(pic6,posX,150,70,70)
  img3=image(pic3,posX, posY-300,150, 200)
  if (playAnim) {
  posX=constrain(posX+1,0,rightwall-30)
  posY=constrain(posX-1,posY,height-50)
  }
} 

How can I cancel axios request by token?

I’m trying to cancel axios request by token in useEffect:

// http-request.js

export const cancelelationSource = axios.CancelToken.source();

export const get = endpoint => {
  return axios.get(endpoint, {
    headers: { ...headers },
    timeout: 20000,
    cancelToken: cancelelationSource.token
  })
    .then(response => response.data)
    .catch(e => {
      console.log(e);
    });
}

then in component:

import { get, cancelelationSource } from './http-request';

const About = () => {
  useEffect(() => {
    get('http://localhost:3001/test2').then(data => console.log(data))
  }, []);
  return (
    <h1>About</h1>
  )
}

const App = () => {
  useEffect(() => {
    get('http://localhost:3001/test').then(data => console.log(data))

    return () => cancelelationSource.cancel();
  }, []);

  return (
    <div>
      <Link to="/about">About</Link>
    </div>
  )
}

render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="/about" element={<About />} />
    </Routes>
  </BrowserRouter>,
  document.getElementById('root')
);

request cancelation works well when I click on the About link. but second API fetch doesn’t work in component <About />

I think axios cancels all requests… I want cancel previous requests but new request should be able to fetch data after change pages or redirect!

Regex appears correct but after passing to javascript replaceAll function it doesnt remove digits in the beggining as expected

I have a regex that I run on a text to remove digits before a “.” as well as some random characters that may appear after it. This regex matches everything i need it to match which I confirmed in regex101.com. However when I pass it to my javascript function as a parameter to the replaceAll() function, the text returned still has some numbers at the end. After countless hours searching online, i still don’t understand why this is happening. Does anyone know the cause?

Regex entered in regex101.com

(^[+-]?d+(.|s|-|)|(s-.)|(s.)?)+(^dd|[^u4E00-u9FA5|a-zA-Z|/:«»|0-9|();n]|d*[.])

Sample text:

11.君曰
1100.君曰
11.君曰
情奴(新版)
我在未来等着你
11.君曰
11.君曰
11678.君曰
11- -.情海孤舟
11 爱 .情海孤舟

Current output from my js function

updatedText = updatedText.replaceAll(/(^[+-]?d+(.|s|-|)|(s-.)|(s.)?)+(^dd|[^u4E00-u9FA5|a-zA-Z|/:«»|0-9|();n]|d*[.])/g, "");

output:
君曰
君曰
君曰
情奴(新版)
我在未来等着你
君曰
君曰
君曰
11情海孤舟
11爱情海孤舟

Any help in explaining why the 11’s are still in the output would be awesome! Thanks in advance.

blank map with gray background while using react-map-gl in production build (even after trying all 3 solutions from mapbox official)

I am not able to display map properly in production, while using react-map-gl in create-react-app. App is working fine on localhost but it throws errors in the console while running in production.
I have tried all the 3 solutions mentioned in official mapbox docs https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling

I first tried these solutions one by one separately, and then all 3 solutions simultaneously, but none of these 4 attempts worked.

I have attached the screenshot of console errors below along with live URL of my production site and github code.

Live URL: https://parking-app-fyp.vercel.app
github code: https://github.com/iAmZubair00/parking-app-fyp

screenshot of console error

I am also adding 3 pieces of code related to 3 solutions for your convenience

import mapboxgl from "mapbox-gl";
// eslint-disable-next-line import/no-webpack-loader-syntax
import MapboxWorker from "worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker";
mapboxgl.workerClass = MapboxWorker.default;
module.exports = {
  babel: {
    loaderOptions: {
      ignore: ["./node_modules/mapbox-gl/dist/mapbox-gl.js"],
    },
  },
};
"browserslist": {
    "production": [
      ">0.2%, not dead, not ie 11, not chrome < 51, not safari < 10",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }

How to reformat json in java script [closed]

json that i get from api

[
  {
    "value": "45",
    "timestamp": "2022-01-21T00:00:12.847",
    "id": "cabc6d20-f305-4a1c-888c-dca2043a06ba",
    "ru": "R401",
    "area": "area-1",
    "unit": "33",
    "equipment": "radio",
  },
]

what i want

[
 {
   "id": "946362d4-5e65-421f-8669-c89fa37bb6e7",
   "equipment": "radio",
   "area": "area-1",
   "value": "45",
  },
]

what i want is the order is change, and only pick some key.

thanks for help

Kibana not loading due to unsafe script

I have upgraded my elastic / kibana stack from 7.12.1 to 7.16.2

Unfortunately and despite the fact that elasticsearch is now healthy, kibana is not loading due to a js error:

login:1 Refused to execute script from 'https://my-kibana.com/login?next=%2F39457%2Fbundles%2Fplugin%2Fdata%2Fdata.plugin.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

enter image description here

(there are other errors like this as well)

Any suggestions?

Declare variable inside array’s element in javascript

Does anyone can explain why this code works in javascript ?

let people = [
  "Jeremy",
  "Male",
  (address = [(domicile = [{ province: "jakarta", city: "jakpus" }])]),
  (origin = [{ provinceOrigin: "Lampung", cityOrigin: "Bandar Lampung" }]),
];
console.log(address); //[ [ { province: 'jakarta', city: 'jakpus' } ] ]

does this code declare a variable inside array’s element ? but why i cannot declare the variable using let, const, or var ?

Vue.js and javascript, how should I append the correct string to my URL?

I made a website.

I currently have a form and a link next to the form. When the user clicks on the link, whatever is typed in that form will be added to the url path of /funpage/, and become the new URL path. So for example, If the user types something like /hey/hi then clicks on the link. The link will take the user to a URL like /funpage/hey/hi. Another example, Is if the user types something like /hellooy/hi/hey/whatsup/hi then clicks on the link. The link will take the user to a URL like /funpage/hellooy/hi/hey/whatsup/hi.

The issue is that my Vue.js application with vue router, will think that the user is going to a new webpage, because the user inputted backslashes that get added to the URL and act like it is a whole new path.

My solution is to write a regex like ///g and use the replace function in Javascript, for the user’s input into the form, which gets rid of any backslash characters. So when the user types something like /hey/hi and clicks on the link, it will just take them to /funpage/heyhi which is what I want.

However I am sure that there are more characters that you don’t want to be entered into a URL, that I know the user could input and would break it. I know about encodeURIComponent but this seems to be only used If you want to purposely add query params.

Does someone possibly have a regex better than ///g to escape all characters that shouldn’t be in a URL? or a better solution perhaps.

Thank you!

Cannot read properties of undefined (reading ‘fetch’) on guild.members.fetch()

I am working on setting a script that will cycle thorough all the members in a guild without using the cache system. I am getting an issue where when I use guild.members.fetch() it treats guild.members as undefined. I know it isn’t because I am currently logging guild.members and it is giving me a GuildMemberManager object. I don’t understand when once I use fetch() on it, it is suddenly being viewed as undefined.
Here is a screenshot of the entire error message

function addMissingJsons(message, bot) {
    bot.guilds.fetch("id").then(guild => {
        console.log(guild.members);
        guild.memebers.fetch().then(members => {
            console.log(members);
        });
    });
}