then() and catch() returning Promises, pointing to same instance in memory

Doubt:

According to MDN docs, then() and catch() returns a Pending Promise Immediately and if the handler functions doesn’t return anything, the returned promise becomes fulfilled with undefined value. So, if current Promise is P0, then() (attached to P0) returns promise P1 and catch() (also directly attached to P0) returns promise P2. Initially P1 and P2 both would be in “pending” state. Now, if catch()’s handler run, P2 will become fulfilled with undefined value. Since then()’s handler never runs will P1 always be in “pending” state? If not, then why is it’s state changed and how is it changed? (What is the flow of control of code that changes the state)

Code:

const p0 = new Promise((resolve,reject) => {
    let num = Math.random();
    setTimeout(()=> {
        if(num >= 0.5) {
            console.log("Resolved");
            resolve("Promise resolved");
        }
        else {
            console.log("Rejected");
            reject("Promise rejected");
        }   
    }, 7000);
});

const p1 = promise.then(function (resolveValue) {
    console.log("Then handler was executed");
    console.log(resolveValue);
})
console.log("P1");
console.log(p1);

const p2 = promise.catch((rejectValue) => {
    console.log("Catch handler was executed");
    console.log(rejectValue);
})
console.log("P2");
console.log(p2);
setTimeout(()=> {
    console.log("P1");
    console.log(p1);
}, 12000);
setTimeout(()=> {
    console.log("P2");
    console.log(p2);
}, 17000);

Output:

P1

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined

P2

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined

Rejected
Catch handler was executed
Promise rejected

Uncaught (in promise) Promise rejected
Promise.then (async)        
(anonymous) @   app2.js:15

P1 
Promise {<rejected>: 'Promise rejected'}
[[Prototype]]: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: "Promise rejected"

P2
Promise {<fulfilled>: undefined}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined

Set a input value HTML and submit, using console

I have a problem, on my work i need create a code for send barcodes in webaapp, submit and get response, but i don’t have permission install softwares in computers, I can only access the webapp within the company’s computers due to a network limitation. Is there any way for me to do all this using just the Google Chrome devtools console, and generate a json with the data I collect?

My initial idea was to use Python and Selenium, but that won’t be possible…

How to show JSON object in a HTML modal? JSON object is a multi row-column table retrieved from DB

i want to show my table made of unknown rows and 5 columns in a modal. i’ve tried many ways explained below after the code:

The start button:

<button class="btn btn-warning" onclick="EditHistory('@item.OriginalCode')">Start</button>

JS:

function EditHistory(OriginalCode)
        {
            var postData = {
                'SearchKey': OriginalCode,
            }
            $.ajax({
                contentType: 'application/x-www-form-urlencoded',
                dataType: 'json',
                type: "POST",
                url: "Index2",
                data: postData,
                success: function (data) 
                {
                    if (data.isSuccess == true) 
                    {
                        const b = [];
                        const c = [];
                        const d = [];
                        const e = [];
                        const f = [];
                        for (let i=0; i<data.data["countHistory"]; i++) //countHistory is number of rows in my table retrieved from DB.
                        {
                            const a = data.data["aPsHistory"][i]; //aPsHistory is a list in a dictionary sent by JSON. it's my table retrieved from DB
                            b[i] = a["originalCode"];
                            c[i] = a["currentCode"];
                            d[i] = a["changes"];
                            e[i] = a["editTime"];
                            f[i] = a["userId"];
                            
                            document.getElementById("OriginalCode").innerHTML = b[i];
                            document.getElementById("CurrentCode").innerHTML = c[i];
                            document.getElementById("Changes").innerHTML = d[i];
                            document.getElementById("EditTime").innerHTML = e[i];
                            document.getElementById("UserId").innerHTML = f[i];
                        
                        $('#EditHistory').modal('show');
                        
                    }
                    else 
                    {
                        swal.fire(
                            'هشدار!',
                            data.message,
                            'warning'
                        );

                    }
                },
                error: function (request, status, error) 
                {
                    alert(request.responseText);
                }

            });
        }

The Modal:

<div class="modal fade" id="EditHistory" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLongTitle">Discription</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="col-xl-12 col-lg-12 col-md-12 mb-1">
                        <table class="table table-striped table-bordered zero-configuration dataTable" id = "DataTables_Table_0" role = "grid" aria - describedby="DataTables_Table_0_info" >
                            <thead style="font-size:small;" >
                                <tr role="row" >
                                    <th class="sorting" tabindex = "0" aria - controls="DataTables_Table_0" rowspan = "1" colspan = "1" aria - label="کد انحصاری ابتدایی: activate to sort column ascending" style = "width: 401px;" > کد انحصاری ابتدایی </th>
                                    <th class="sorting" tabindex = "0" aria - controls="DataTables_Table_0" rowspan = "1" colspan = "1" aria - label="کد انحصاری کنونی: activate to sort column ascending" style = "width: 401px;" > کد انحصاری کنونی </th>
                                    <th class="sorting" tabindex = "0" aria - controls="DataTables_Table_0" rowspan = "1" colspan = "1" aria - label="تغییرات: activate to sort column ascending" style = "width: 401px;" > تغییرات </th>
                                    <th class="sorting" tabindex = "0" aria - controls="DataTables_Table_0" rowspan = "1" colspan = "1" aria - label="تاریخ ویرایش: activate to sort column ascending" style = "width: 401px;" > تاریخ ویرایش </th>
                                    <th class="sorting" tabindex = "0" aria - controls="DataTables_Table_0" rowspan = "1" colspan = "1" aria - label="کاربر ویرایش کننده: activate to sort column ascending" style = "width: 401px;" > کاربر ویرایش کننده </th>
                                </tr>
                            </thead>
                            <tbody style = "font-size:smaller;" >
                                <tr role="row" class="odd" >
                                    <td id="OriginalCode" > </td>
                                    < td id = "CurrentCode" > </td>
                                    < td id = "Changes" > </td>
                                    < td id = "EditTime" > </td>
                                    < td id = "UserId" > </td>
                                </tr>
                            </tbody>
                        </table>  
                    </div>
                </div>
                <div class="modal-footer">
                    <a class="btn btn-secondary" data-dismiss="modal">close</a>
                </div>
            </div>
        </div>
    </div>

I wish if i could sent JSON data to a global variable defined in C#, then write a @foreach on it in HTML and see the result in modal. but in JS i cannot see C# variables to put the JSON data in it (at least i tried).

OR

if i could put the JSON data to a global JS variable, but this variable cannot be seen in HTML! remember that i want to run a @foreach loop on it in HTML, so if i use getElementById method, i cannot use it in loop or any condition. or maybe idk how to do this? for example is something like this possible?:

@foreach (var item in HTML Tag Attribute (Id))

i want something like this. i ran the code above and it worked fine. but the problem is that my code is ok for only 1 row of 5 column data. if i want to put a for loop in HTML modal to add more rows to the table, idk how to put the counter? up to what number my for loop should count? because my table rows count is unknown. i can get the count in JSON (countHistory) but idk how should i send it to the HTML to put it as the counter in for loop.
or maybe there is another better way to show JSON data in modal. please help me. thanks

How do I get cancelOrder() to work? (wix-velo API)

Here’s the API backend reference:
https://www.wix.com/velo/reference/wix-pricing-plans-backend/orders/cancelorder

I’ve installed Wix Pricing Plans to my Wix-site (no code required), but it does not give my members the option to cancel their recurring plan.

I don’t want to cancel their plans manually, upon request, I’m looking to coding to handle it immediately, upon request (eg. onClick of a button).

The linked reference gives this example:

Cancel an order immediately, bypassing permission checks

import { orders } from 'wix-pricing-plans-backend';

/* Sample orderId value: 'a8c4a1b2-b5e8-4b33-9693-057ec93e9a27'
 * 
 * Sample effectiveAt value: 'IMMEDIATELY'
 * 
 * Sample options value:
 * {
 *   suppressAuth: true
 * }
 */

export async function myCancelOrderWithOptionsFunction(orderId, effectiveAt, options) {
  try {
    const order = await orders.cancelOrder(orderId, effectiveAt, options);

    return order;
  } catch (error) {
    console.error(error);
  }
}

// Returns a promise that resolves to void

I’ve tried to implement this, but I’m new to working with backend to frontend code, and don’t know how to do it.

I know how to add a backend module, but I don’t know what code to add there and what corresponding code to add in the frontend.

I hope you all can help.

Ultimately I would need to get all orders connected to the wixUsers.currentUser.id, and then run the cancelOrder() function on those orderId‘s

Cheers.

All component children of must be a when is used

I have simple React project with next hierarchy of components:

Main component(here I call routing service and render components in a routes):

const App: React.FC = () => {
    return <BaseLayout>{RoutingService.getRoutes()}</BaseLayout>;
}

export default App;

Code of routing service:

class RoutingService {
    static getRoutes = (): React.ReactNode => {
        return (
            <Routes>
                <Route key={makeRandomKey()} path={PATHS.ROOT_PATH} element={<MainPage/>}/>
                <Route key={makeRandomKey()} path={PATHS.AUTH_PATH} element={<LoginPage/>}/>
                <Route key={makeRandomKey()} path={PATHS.NOT_FOUND_PATH} element={<UnderConstructPage/>}/>
                <ProtectedRoute path={PATHS.SEARCH_HISTORY_PATH} element={<SearchHistoryPage/>}/>
                <ProtectedRoute path={PATHS.USER_CABINET_PATH} element={<UserCabinetPage/>}/>
            </Routes>
        );
    };
}

export default RoutingService;

So what I want to perform – to have some opened routes(pages) for all users(logged in and non-logged in) like main page, not found and auth pages.
But I have pages where I need to restrict access for non-logged users. for that purpose I created ProtectedRoute component which should redirect user to auth page when he isn’t logged in and tries to access pages which require login.

interface ProtectedRouteProps {
    path: string;
    element: React.ReactNode;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({path, element}) => {
    const isAuthenticated: boolean = useSelector((state: RootState) => !!state.user.userData?.auth?.token);

    return isAuthenticated ?
        <Route path={path} element={element}/> : <> <Navigate to="/auth" replace/></> ;
};

export default ProtectedRoute;

Unfortunately, I’m getting error:

router.ts:5 Uncaught Error: [ProtectedRoute] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
    at invariant (router.ts:5:1)

Seems <Navigate> in ProtectedRoute component provokes this error, but I don’t know, how to implement this redirect correctly. How to fix that?

document.head.insertAfter() is not a function

This is the head tag.

<head>
    <meta charset="utf-8" />
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="admin-template/assets/img/favicon/favicon.ico"/>

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Public+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet"/>

    <meta id="template-css-anchor" name="template-css-anchor" content="This is where template css will be loaded"/>

    <!-- Icons -->
    <link rel="stylesheet" type="text/css" href="%PUBLIC_URL%/admin-template/assets/vendor/fonts/boxicons.css"/>
    <link rel="stylesheet" type="text/css" href="%PUBLIC_URL%/admin-template/assets/vendor/fonts/fontawesome.css"/>
    <link rel="stylesheet" type="text/css" href="%PUBLIC_URL%/admin-template/assets/vendor/fonts/flag-icons.css"/>
</head>

I want to insert new css files after meta with id="template-css-anchor"

I am doing it like this:-

var templateCssAnchor   = document.querySelector('#template-css-anchor');

const cssBoxIcon        = document.createElement('link');
cssBoxIcon.id           = 'boxicon-css';
cssBoxIcon.href         = baseUrl + 'admin-template/assets/vendor/fonts/boxicons.css';
cssBoxIcon.rel          = 'stylesheet';
cssBoxIcon.type         = 'text/css';

if (!document.getElementById('boxicon-css')) {
    document.head.insertAfter(cssBoxIcon, templateCssAnchor);
    //document.head.appendChild(cssBoxIcon);
}

I am getting error :-

document.head.insertAfter is not a function.

However, document.head.appendChild(cssBoxIcon); seems to be working fine.

Why?

Redirect link customization

I’m using vitalsource as a redirect source but the issue is that it cant be customized, and can only redirect to a main website. the redirect URL is “https://bc.vitalsource.com/books/9781119493440R150?bc_token=f9984a30-8eae-013c-8d06-0e40f9c629f8&relaunch_vbid=9781119493440R150&course_dash_relaunch=true&dash_student_pay=true”, where “9781119493440R150” is the code I am trying to extract. Right now, it redirects me to a website I am hosting on github at www.bahaa-aea.github.com/aafaq, but the target https://gust.aafaqeducation.com/ (the numbers i typed)

The number in the redirect link does change based on product, and I would like to know if theres any way to extract it before it redirects me to the github link so I can run custom code to input itinto the website I want.

When It redirects me, the console simply says “ISBN not found in the URL.” which is an error code i programmed into it, I think its just trying to read the url that it sends me to rather than the redirect link.

Here is my current JS code:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ISBN Redirect</title>
</head>
<body>

<script>
  // Get the current URL
  var currentUrl = window.location.href;

  // Extract ISBN from the current URL
  var isbnMatch = currentUrl.match(/books/(d+)/);
  if (isbnMatch && isbnMatch[1]) {
    var isbn = isbnMatch[1];

    // Construct the new redirected link
    var redirectedLink = "https://gust.aafaqeducation.com/" + isbn;

    // Redirect to the new link
    window.location.href = redirectedLink;
  } else {
    console.error("ISBN not found in the URL.");
  }
</script>

</body>
</html>

module.exports parameters in functions not getting detected by intellisense

So to showcase this problem, I wrote an example index.js and a commandExample.js that executes every time a message is sent by a user that isn’t a bot. index.js contains the following code:

const { Client, IntentsBitField, Events} = require("discord.js");
const {token} = require("./config.json");
const cmd = require("./commandExample.js");

const client = new Client({intents: [IntentsBitField.Flags.GuildMembers, IntentsBitField.Flags.GuildMessages, IntentsBitField.Flags.Guilds, IntentsBitField.Flags.MessageContent]});
var prefix = ",";

client.on(Events.MessageCreate, (message) => {
    //checks if the message author is a bot or not
    if (message.author.bot) return;
    //passing the message parameter to the module.exports then executing the code
    cmd(message);

})



client.login(token);

as you can see we require the function inside the module.exports, but the problem is, for some reason intellisense doesn’t autocomplete the message object’s params, here’s a screenshot of the problem.

it’s supposed to give me the params and functions of the message object, but it doesn’t (this has nothing to do with the param’s name being “msg” in the commandExample.js and being “message” in the index.js file) so for example, if i do message. in the event listener, it gives me all the functions and params in the message object, but if i do msg. in the cmd function, it doesn’t give me anything. making the event listener inside the cmd function is not practical at all because there is a max amount of them and manually setting the max amount of them sometimes just breaks the bot and makes it extremely slow.
so yeah i’m wondering if somebody with more coding experience than me can give me a practical fix to this problem since it has been annoying me for a long time, thank you for reading this 😀

Empty object passing in axios – Vue js

I am sending an object from this.productDetails as part of an axios.post() request. Upon inspecting the payload in the browser’s network tab, I observe that the object is devoid of any data.

Here’s the Axios call:

        async addProduct(){
            console.log('product_details', this.productDetails)
            const apiResponse = await axios.post('add_product',{
                productDetails : this.productDetails
            })

            const response = apiResponse.data
        },

I have consoled it by: console.log('product_details', this.productDetails) and it does has the actual object: console.log of the object I am passing

This is my Laravel route:

    Route::post('add_product',[PackageSubscriptionController::class, 'addProduct']);

Here’s the Network:
enter image description here

how check collision with javascript?

Hi I want check collision between Div and Img tag with java Script.
I have Div with id name is MainDiv. in this div there is too many img tag with position absolute and deferent width and height.
aslo there is div id name selection.
the scenario is when user start draw rectangle (selection) by left click in the mainDiv if the selection has collision img tag in the mainDiv the selection background color turn too red and if not remain green.

I write this JavaScript right now:

     const MainDiv = document.getElementById('MainDiv');
 const selection = document.getElementById('selection');
 const dimensionsInfo = document.getElementById('dimensionsInfo');
 let startX, startY, startOffsetX, startOffsetY;
 let width,height;
 
     MainDiv.addEventListener('mousedown', startDrawing);
     MainDiv.addEventListener('mousemove', drawRectangle);
     MainDiv.addEventListener('mouseup', stopDrawing);
 

 function startDrawing(event) {

     if (getComputedStyle(event.target).cursor === 'pointer') {
         return;
     }

     startX = event.clientX;
     startY = event.clientY;
     startOffsetX = event.offsetX;
     startOffsetY = event.offsetY;

     selection.style.display = 'block';
     dimensionsInfo.style.display = 'block';
 }

 function drawRectangle(event) {
     if (startX && startY) {

         const MainDivOffsetX = MainDiv.getBoundingClientRect().left;
         const MainDivEndDrawX = MainDiv.offsetWidth + MainDivOffsetX;

         const MainDivOffsetY = MainDiv.getBoundingClientRect().top;
         const MainDivEndDrawY = MainDiv.offsetHeight + MainDivOffsetY;

         if (event.clientX >= MainDivOffsetX && event.clientX <= MainDivEndDrawX) {
             width = (event.clientX - startX); 
         }

         if (event.clientY >= MainDivOffsetY && event.clientY <= MainDivEndDrawY) {
             height = (event.clientY - startY);
         }

        
         const area = Math.abs(width * height);
         const sum = Math.abs(area * 100).toLocaleString();


         selection.style.width = Math.abs(width) + 'px';
         selection.style.height = Math.abs(height) + 'px';
         selection.style.left = width < 0 ? event.clientX + 'px' : startX + 'px';
         selection.style.top = height < 0 ? event.clientY + 'px' : startY + 'px';

         const startAdsX = startX < event.clientX ? startOffsetX : startOffsetX - Math.abs(width);
         const startAdsY = startY < event.clientY ? startOffsetY : startOffsetY - Math.abs(height);

         dimensionsInfo.style.left = event.clientX + 'px';
         dimensionsInfo.style.top = event.clientY + 'px';



         const targetElement = document.elementsFromPoint(event.clientX, event.clientY);
         let intersectsWithImage = false;

         for (let i = 0; i < targetElement.length; i++) {
             if (targetElement[i].tagName === 'IMG') {
                 intersectsWithImage = true;
             }
         }
         if (intersectsWithImage === true) {
             selection.style.backgroundColor = 'rgba(255, 127, 127, 0.3)';

         }
         else{
             selection.style.backgroundColor = 'rgba(144, 238, 144, 0.3)';
        

         }
         
         
     }
 }

in this code I use document.elementsFromPoint to check if the cursor position in image tag or not. but in this way the color only turn red when cursor in the img and if the curson outside but the collision is occurred the color is remain green.
also I do not want use queryselectorsall because I have too many img tag in mainDiv and if I use it take very processor power.
I try this too:

let targetElement;
   for (let x = startAdsX; x <= startAdsX + width; x++) {
       for (let y = startAdsY; y <= startAdsY + height; y++) {
           targetElement = document.elementsFromPoint(x, y);
           for (let i = 0; i < targetElement.length; i++) {
               if (targetElement[i].tagName === 'img') {
               intersectsWithImage = true;
                 }
             }
}
}

in this way i get all the point of selection area and compare for collision. but in this way there is too many process.
so how to fix this?

How to detect the code smell in my newly created code in online/VS Code [closed]

I need to find the code smells in my program (HTML,CSS,JS).Is there any online tools to detect CodeSmell?

I have Installed SmellyGPT in my Visual Code Studio, but I’m still unaware how to detect the code smell for my project using API.

In my project involving HTML, CSS, and JavaScript, I’m looking to identify and rectify potential code smells. Are there any online tools or APIs specifically designed to detect code smells in these languages? I’ve installed the SmellyGPT plugin in Visual Studio Code but require guidance on how to effectively use its API or similar tools to perform code smell analysis in my project. Could you provide insights or recommendations on available tools, integrations, or methods to effectively detect and address code smells in my HTML, CSS, and JS codebase?”

Query for web design [closed]

Will web development have any role in the future or will it be removed with the advent of AI ?

Because I have just started web development.
Please help me and replay it as soon as possible and you can also tell me what you have to say.

Uncaught TypeError: Failed to resolve module specifier “openai”. Relative references must start with either “/”, “./”, or “../”

I was trying to use OpenAI Api and wrote a very simple html and js code to test if it’s working. But I get an error in the browser console :

Uncaught TypeError: Failed to resolve module specifier “openai”. Relative references must start with either “/”, “./”, or “../”.

Here’s the simple JS code that I used to test the API (API Key hidden for obvious reasons) :

import OpenAI from "openai";

const openai = new OpenAI();
async function main() {
  const completion = await openai.chat.completions.create({
    Authorization: Bearer `${OPENAI_API_KEY}`,
    messages: [{ role: "system", content: "You are a helpful assistant." }],
    model: "gpt-3.5-turbo",
  });

  console.log(completion.choices[0]);
}

main();

In the intex.html file I just have a normal base code and a script tag :

<script type="module" src="script.js"></script>

How do I resolve this simple code to run. The JS code is direclty from OpenAI docs.

how to perform action on double click on a button using Angular JS

using this I am checking right click on my button how can I check double click on my button

`

        app.directive('rightClick', function ($parse, $mdMenu) {
           return function (scope, element, attrs) {
           var fn = $parse(attrs.rightClick);
           element.on('contextmenu', function (event) {
            event.preventDefault();
            scope.$apply(function () {
            fn(scope, { $event: event });
          });
          event.stopPropagation();
        });
       };
     });


      
      
     <button right-click="$mdMenu.open($event)" id="{{element.id}}">

`