Javascript – transform a “then function” to an “async function” [closed]

I try to change a “function f(input).then(function(output) …) in a form like : “output = await something”

I’m deal with the (tsayen)dom-to-image library … (in the brwser, not with nodes.js)
I must deal with multiple DOMelement
So, I wish to could make : dataUrl = await F(HTMLElement)

with the definition of the librairy, I should script something like :

domtoimage.toPng(HTMLElement1).then(function(dataUrl1){ {do with dataUrl1} domtoimage.toPng(HTMLElement2).then(function(dataUrl2){ (do with dataUrl2} domtoimage.toPng(HTMLElement3).then ... etc ...

I DON’T know how much HTMLElements I have to deal with …
So, I wish “dataurl = await someasyncfunction(HTMLElement)” in order to be able to script a loop …

I’ve tried :

async function dom2url(HtmlElem) { (resolve,reject) => { domtoimage.toPng(this.HtmlElem).then(async function(dataUrl){ return await dataUrl; })}; }

            then 

dataUrl = await dom2url(htmlElem) but don't match

I’ve read so many times “async / await”, “Promises” and “Arrow function” that my head is full ! Please : could you help me ? not to give me somes references to these functions, of course 🙂

Range slider’s thumb out of control

””

 let drag1 = document.getElementById("circle");
    let drag2 = document.getElementById("circle2");
    let isDragging = false;
    let initialX;

function onMouseDown(e) {
    initialX = e.clientX - drag1.getBoundingClientRect().left;
    isDragging = true;

    function mouseMove(e) {
        if (isDragging && e.buttons===1) {
           e.preventDefault();
           drag1.style.left = e.clientX - initialX + 'px';
        } 
    }
    function mouseUp(e) {
        isDragging = false;
        drag1.removeEventListener("mousemove", mouseMove,true);
        drag1.removeEventListener("mouseup" , mouseUp,true);
    }

    drag1.addEventListener("mouseup", mouseUp,true);
    drag1.addEventListener("mousemove", mouseMove,true);
    e.stopPropagation();
};

drag1.addEventListener("mousedown", onMouseDown);

””

The situation now is like mouseup event cannot be recognized or the eventListener cannot be removed after the button is really released (before i added the condition e.buttons===1).
Before that, when i put the mouse near the indicator(or someone else call it a thumb),
the thumb will go right in a short distance. After i add the condition control, it becomes better-at least will not move by itself again when the mouse come close. However, it seems the root cause is still there, the thumb cannot be dragged to left side and it can only be dragged to right side by a little bit distance(same as the distance it moved when i put the mouse close to it.)

Can someone teach me what I’ve done wrong? I tried several solution to try to solve it however nothing changed. Here below are those action tried.

  1. As I wonder function mouseUp or the EventListener added to it cannot be run normally because of scope issue, so i tried put funtion mouseMove() and mouseUp() out of function onMouseDown(). However nothing changed.

  2. Found a way on web that is adding a mouseleave EventListener for before the stopPropagation but it still fails

  3. Add the .removeEventListener at first sentence in function onMouseDown(). Tried to stop if there is any non-removed Listener, but it still fails

Could any master can save me on this? Thank you so much.

I get AbortError: OTP retrieval was cancelled before receiving SMS

import loginServices from "@/services/login/ServicesLogin";
import React, { useState } from "react";
import toast from "react-hot-toast";

const TestPage = () => {
  const [otpValue, setOtpValue] = useState("");

  const handleSendOTP = () => {
    loginServices
      .SendVerifyCodeLogin("09361651719")
      .then((res) => {
        if (res) {
          if (navigator && navigator.credentials) {
            const ac = new AbortController();
            navigator.credentials
              .get({
                otp: { transport: ["sms"] },
                signal: ac.signal,
              })
              .then((otp) => {
                setOtpValue(otp.code);
              })
              .catch((err) => {
                console.log(ac.signal);
                console.log(err);
              });
          }
          toast.success(res.result);
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };

  return (
    <div className="mt-20 mr-5">
      <input
        type="text"
        className="bg-slate-300"
        autoComplete="one-time-code"
        value={otpValue}
        onChange={(e) => setOtpValue(e.target.value)}
      />
      <button onClick={handleSendOTP}>send</button>
    </div>
  );
};

export default TestPage;

This is a test page for otp autofill. I have checked the sms and the compatibililty of the browser everything seems to be fine but I get this error as soon as it gets to the promise for navigator.creditentials.The error occurs before even getting the sms. what could be the issue?

Frequently updated data in MongoDB is not visible in Open Search via Monstache syncing

I have mongodb database for storing all the data, from few collections I’m syncing MongoDB database data to AWS Open Search via Monstache Plugin. For normal case working fine but when some of my mongodb data updated so frequently like Status field in that case that status is not updated into the AWS Open Search but in MongoDB is updated correctly.

Here is monstache logs

  1. First entry when I have no status:
{
    "doc": {
        "CdxActivityId": 417462,
        "CdxClusterId": "services.*.com",
        "CdxCreatedAt": "2025-03-03T06:15:28.000Z",
        "InternalGroupId": "*",
        **"__v": 0,**
        "contentType": "application/octet-stream",
        "createdAt": "2025-03-03T05:15:28.954Z",
        "linkedActivities": [],
        "location": "IE",
        "oplog_date": "2025/03/03 05:15:28",
        "oplog_ts": {
            "T": 1740978928,
            "I": 7
        },
        "restartEvents": [],
        "restartHistory": [],
        "status": "No statuses"
    },
    "doc_as_upsert": true
}

In mongodb we have __v field in which we are maintaining the version and in first case __v=0 I got no status which updated correctly in Open search via monstache syncing.

But very frequently when I got next status like Success then that status not present in open search

{
    "doc": {
        "CdxActivityId": 417462,
        "CdxClusterId": "services.*.com",
        "CdxCreatedAt": "2025-03-03T06:15:28.000Z",
        "InternalGroupId": "*",
        "__v": 2,
        "contentType": "application/octet-stream",
        "createdAt": "2025-03-03T05:15:28.954Z",
        "linkedActivities": [],
        "location": "IE",
        "oplog_date": "2025/03/03 05:15:29",
        "oplog_ts": {
            "T": 1740978929,
            "I": 19
        },
        "restartEvents": [],
        "restartHistory": [],
        "status": "Success"
    },
    "doc_as_upsert": true
}

“__v”: 2 in this mongodb data version I got success status but this version is not present it into AWS open search.

I tried so many thing but no luck, Below is my toml configuration currently I have

resume-from-timestamp = 1739336325
    verbose = true
    resume = true
    replay = true
    index-oplog-time=true
    index-as-update = true
    elasticsearch-max-docs = 1
    elasticsearch-max-conns = 5
    elasticsearch-max-seconds = 5
    gtm-settings = {buffer-size = 1024, buffer-duration = "2s"}

I’m using Monstache 6 docker image with Javascript.

Can someone please help how to overcome this problem?

I tried to use external option but did not worked, May be I did something wrong!

How can I create a Python script to automate clicks in Geometry Dash?

I’m trying to create a simple Python script that can simulate mouse clicks at a specific interval to auto-play Geometry Dash on Windows 10.

I’ve tried using the pyautogui library to click repeatedly, but it doesn’t seem to sync well with the game’s frame rate, and sometimes the clicks are delayed or skipped.

Here’s a basic version of my code:

import pyautogui
import time

time.sleep(5) # Time to switch to the game window
while True:
pyautogui.click()
time.sleep(0.1) # 10 clicks per second
The problem:

The timing isn’t consistent, which causes the gameplay to break.
The CPU usage sometimes spikes during the loop.
Is there a better way to handle precise timing for clicks in games like Geometry Dash? Should I use another library or method to sync the clicks with the game’s frame rate (60 FPS)?

Any advice, code improvements, or alternative solutions would be greatly appreciated.

Thanks!

I used the pyautogui Python library to simulate mouse clicks. I wrote a simple loop that clicks at fixed intervals (every 0.1 seconds) to try and match the rhythm of the game.
Here’s the code I used:

import pyautogui
import time

time.sleep(5) # Time to switch to the game window
while True:
pyautogui.click()
time.sleep(0.1)
I also tried adjusting the sleep time to sync better with the game but couldn’t find a stable timing.

Why newValue is same as currentValue here? [duplicate]

I am learning js new.

let currentValue = 10;
let newValue = currentValue++;
console.log(newValue) // returns 10

Here I have declared a current value variable and stored 10 there.Then I declared a newValue variable and assigned currentValue using ++ operator to increase the value of currentValue and store it. But its returning the previous value in new value. Why is this happening?
I am a newbie in js.

Refactor this function to reduce its Cognitive Complexity with object for loop [duplicate]

With my function I am stuck up with following error:

Refactor this function to reduce its Cognitive Complexity from 30 to the 15 allowed. [+11 locations]sonarqube(typescript:S3776)

But have no clue to fix this. any advice please? I see there is other answers, I look help for my scenario.

here is my code:

const filterFormatter = async (
  Queries: Record<string, string>,
  Schema: any
) => {
  const filtersFromURI = [];
  for (const [key, keyValue] of Object.entries(Schema)) {
    const operator = `${key}Operator`;
    const isFieldExit = has(Queries, operator);
    const value = has(keyValue, "alias")
      ? Queries[keyValue.alias]
      : (keyValue as string);
    const isDate = Schema[key][Queries[operator]] ?? undefined;
    const isNeedFetch = Schema[key]?.fetch;
    const filedWithKey = { field: key, operator: Queries[operator] };
    if (isFieldExit) {
      if (isNeedFetch && key === "document") {
        const docFilter = await getSelectedDocs({
          ...filedWithKey,
          value: value,
        });
        filtersFromURI.push(docFilter);
      }
      if (!isNeedFetch) {
        if (key === "nationality") {
          filtersFromURI.push(nationalityFilterGen({ ...filedWithKey, value }));
        }
        if (isDate !== undefined) {
          filtersFromURI.push(
            dateFilterGen(Schema, key, Queries, operator, filedWithKey)
          );
        }
        if (!isDate && key !== "nationality") {
          filtersFromURI.push({
            ...filedWithKey,
            value: /,/.test(value) ? value.split(stringToArray) : value,
          });
        }
      }
    }
  }
  return filtersFromURI as GridFilterItem[];
};

Error highlight from sonar

Javascript Tables Not loading after Update

I updated a few plugins and updated the theme and now the javascript tables aren’t loading when the page loads. The table header shows up but the data from the tables doesn’t populate into the tables. I also updated to PHP 8.2

Restored files from earlier in the week but it still didn’t help. I’m hoping to fix the issue rather than loading a complete file & database restore so we don’t have to loose woocommerce orders.

Hover state not working in my react app am using tailwind css v4.0

import React from 'react';
import './index.css';

function App() {
  return (
    <div className="App">
      <h1 className="text-3xl font-bold underline">React App</h1>
      <button className="p-8 m-8 bg-amber-300 text-amber-50 hover:text-amber-950 hover:bg-black ">
        Add
      </button>
    </div>
  );
}

export default App;
// index.css 
@import "tailwindcss";

I tried to reinstall the tailwind css, I tried to create new property in theme as the official website recommended to do.

Konva.js Blocking Google Maps Interactions

I’m using Konva.js as a drawing tool along with Google Maps. This creates two layers: Konva.js on top of Google Maps. However, Konva.js captures all pointer events, preventing interaction with the map.

I’ve tried using event listeners, but they were rejected. I also attempted toggling pointer events on and off with a button, but it’s inconvenient.

How can I resolve this issue?

Using Flutter as a Rendering Engine for Web-like Apps

  1. Our team plans to develop a cross-platform rendering framework based on Flutter.
  2. We have chosen JavaScript as our front-end language to interface with Flutter’s render objects.
  3. We plant to rewrite the flutter’s darr code into c++

I have two questions:

  1. Has anyone done similar work that I can reference?
  2. Is it feasible to convert all Dart code to c++?

Thank you.

how to let the user input the number of tickets sold in a raffle

I have a working js that will pick a random raffle number between 1 & 100 but would like to let the user input the number of tickets sold. I just want to have the max range increased or decreased via text input.

How do I get the user to change the value depicted as 100 ( i <= 100 )

var bingoNumList = [];
for (var i = 1; i <= 100; i++) {
   bingoNumList.push(i);
}

for(let i = bingoNumList.length - 1; i > 0; i--){
  const j = Math.floor(Math.random() * i)
  const temp = bingoNumList[i]
  bingoNumList[i] = bingoNumList[j]
  bingoNumList[j] = temp
}

I just wanted to know what is this number (600) on the left of the message being printed on the console of Developer’s Tools

print of console

What is this? What is the meaning of this number?

I tried to put the mouse on it but it doesn’t display nothing. BTW: this is a Tetris clone and every time I harddrop a piece the number increases by 200.

dont read the following text: “There isnt more to it. I’m just writing more text because stackoverflow doesn’t accept the question being too short”