Why does recursive/nested `setTimeout` does not stop execution without an `else` statement?

I am learning to use recursive setTimeout function.

My task is to create a function that takes 2 number arguments, from and to and prints each number in between to the console, one at the time with the delay of 1 second in between.

My question is, why function printNumbers1 does not stop execution after printing number 4 to the console? The assumption is that the timerID is incorrect, but I do not understand why.

const DELAY = 1000;

const printNumbers1 = (from, to) => {
  let counter = from;
  let timerID = setTimeout(function run() {
    console.log(counter);
    counter++;

    if (counter > to) clearTimeout(timerID);

    // the function not stop the invocation without the `else` statement
    timerID = setTimeout(run, DELAY);
  }, DELAY)
}

const printNumbers2 = (from, to) => {
  let counter = from;
  let timerID = setTimeout(function run() {
    console.log(counter);
    counter++;
    if (counter > to) clearTimeout(timerID);
    else {
      timerID = setTimeout(run, DELAY);
    }
  }, DELAY)
}

printNumbers1(1, 4); // continues to execute after 4th invocation
printNumbers2(1, 4); // stops execution after 4th invocation

retiving data from fetch

The JSON placeholder API gives me the data but open weather API gives error and the error is ‘Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data’
Whats going wrong? and how I can read the weather API data?


      fetch(
        // 'https://jsonplaceholder.typicode.com/posts/1'
        'api.openweathermap.org/data/2.5/weather?q=bhubneshwar&appid=2f5e9a7699ace605d4cbf50f813d7b0b'
      )
        .then((response) => response.json())
        .then((data) => console.log(data));

[Vue warn]: Invalid prop: custom validator check failed for prop “value”. Error shows after succesfully upload file to Firebase

I successfully uploaded a file to Firebase Storage and save the URL link to firestore.

But after the process is completed. The console pop-up this error:

[Vue warn]: Invalid prop: custom validator check failed for prop "value".

and on my screen, it shows up this:

show an error and no file is displayed even though the page is not refreshed.

Again, it only happens after I successfully upload the file.

vue template:

<v-col cols="12" sm="6" md="12">
    <v-file-input
        outlined
        show-size
        prepend-icon="null"
        accept=".pdf"
        v-model="ProgramSummary"
        :rules="required"
        :disabled="processing"
        style="width: 40%;">
        <template v-slot:append-outer>
            <v-progress-circular
                v-if="processing"
                indeterminate
                color="red"
            ></v-progress-circular>
        </template>
    </v-file-input>
</v-col>
<v-col cols="12" sm="6" md="6">
    <v-btn
        color="green"
        dark
        class="float-right"
        @click="uploadProgramSummary">
            Upload
    </v-btn>
</v-col>

script

data: () => ({
   //PROGRAM SUMMARY FILE UPLOAD
   processing: false,
   required: [
       value => !value || value.size < 1000000 || 'File size should not exceeded 1MB!',
   ],
   ProgramSummary: [], 
}),

methods: {
    // SAVE UPLOADED FILE TO FIRESTORE
    onUpload() {
        var uidRef = firebase.auth().currentUser.uid;
        var docRef = firestore
                        .collection("SubworkPackage")
                        .doc(firebase.auth().currentUser.uid)
                        .collection("ProgramSummary")
                        .doc();
        var data = {
            ProgramSummary: this.ProgramSummary,
            uid: uidRef,
            id: docRef,
        };
        firestore
            .collection("SubcontractorRegistration")
            .doc(firebase.auth().currentUser.uid)
            .collection("ProgramSummary")
            .add(data);
    },

    // PROGRAM SUMMARY UPLOAD FILE
    uploadProgramSummary() {
        //LOADING ICON SET TO TRUE
        this.processing = true;
        //DOC REFERENCE OF USER ID
        var uidRef = firebase.auth().currentUser.uid;
        // DOC NAME IS SET TO HAVE A FIXED NAME
        var programSummaryRef = "ProgramSummary.pdf"
        // FILE PATH
        const filePath = `SubcontractorRegistration/${uidRef}/${programSummaryRef}`;
        // METADATA
        const metadata = { contentType: this.ProgramSummary.type };
        //FIREBASE STORAGE ACTION
        FirebaseStorage
            .ref()
            .child(filePath)
            .put(this.ProgramSummary, metadata)
            .then(() => {
                FirebaseStorage
                    .ref()
                    .child(filePath)
                    .put(this.ProgramSummary, metadata)
                    .snapshot
                    .ref
                    .getDownloadURL()
                    .then((url) => {
                        this.ProgramSummary = url;
                        this.onUpload();
                        this.processing = false;
                        alert("Program Summary Succesfully Uploaded!")
                    })
            })
    },
}

I’m using Nuxt and Firebase with Vuetify as the UI library.

Laravel WebSockets pusher in AWS

I create a socket app and it works fine locally
but when I want to test if it will be working in AWS it gives me this error

IlluminateBroadcastingBroadcastException
Pusher error: {“error”:”Unknown app id 12345 provided.”}.

I don’t know does the setting will be different on AWS
or it is a cache issue

this is my sitting

brodcasting.php

'connections' => [

    'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
            'cluster' => env('PUSHER_APP_CLUSTER'),
            //'useTLS' => true,
            //'forceTLS'=>true,
            'encrypted' => true,
            'host' => '127.0.0.1',
            'port'=>'6001',
            'scheme'=> 'http',
            //'curl_options' => [
           //     CURLOPT_SSL_VERIFYHOST => 0,
          //      CURLOPT_SSL_VERIFYPEER => 0,
          //    ]
        ],
    ],

websoket.php

'apps' => [
    [
        'id' => env('PUSHER_APP_ID'),
        'name' => env('APP_NAME'),
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        //'path' => env('PUSHER_APP_PATH'),
        //'capacity' => null,
        'enable_client_messages' => false,
        'enable_statistics' => true,
        
    ],
],

bootstrap.php

 window.Echo = new Echo({
 broadcaster: 'pusher',
 key: env('PUSHER_APP_KEY'),
 //cluster: process.env.MIX_PUSHER_APP_CLUSTER,
 //forceTLS: true,
 wsHost: window.location.hostname,
 wsPort: 6001,
 forceTLS: false,
 disableStats: true, });

getting unique objects from array of nested object and sub properties

i have a script where i am trying to get the unique object based on state from the array of objects

The below scripts works fine, but I have one case where I have nested object in one kind of state has a sub-state, so I want to find the unique from the array of objects and get the unique.

The below snippet I am able to get the first level, but if we see the state => “EF” has a sub_state_details, so I need to get the unique from sub_state_details if state is EF

let inputArray = [{
    state: "AB",
  }, {
    state: "BC",
  }, {
    state: "BC",
  }, {
    state: "CD",
  }, {
    state: "CD",
  }, {
    state: "DE",
  }, {
    state: "EF",
    sub_state_details: {
      state: "EF-1"
    }
  }, {
    state: "EF",
    sub_state_details: {
      state: "EF-1"
    }
  },
  {
    state: "EF",
    sub_state_details: {
      state: "EF-2"
    }
  }
]

let resArr = []
inputArray.filter(function(item) {
  var i = resArr.findIndex(x => (x.state == item.state));
  if (i <= -1) {
    resArr.push({
      state: item.state
    });
  }
  return null;
});

console.log(resArr)

expected output

let output = [{
      state: "AB",
    }, {
      state: "BC",
    }, {
      state: "CD",
    }, {
      state: "DE",
    }, {
      state: "EF-1",
    },{
      state: "EF-2",
    }]

How to get AntD expanded Table to display nested dataSource values

I have to dynamically render some data into antD expandable table. The data is a nested object with various properties –

const values = [
    [name = 'Josh', city = 'Sydney', pincode='10000'],
    [name = 'Matthew', city = 'London', pincode = '20000'],
    [name = 'Roger', city = 'Paris', pincode = '2300'],
]

How can I display this data in an antD table? The dataSource = {values} gives an empty table.
Kindly guide me. How to display nested array values in the antD table?

call again a api when id is passed in react js

i have this callback funtion inside useeffect i want to pass differnt props.id from parent js to this file so i get differnt datas the problem is const res = await axios.get("messages/get-all-messages/?receiver=" + props.id, config ); does not get recalled when i pass a new props.id from parent.js how can i call again this api when i pass a new props.id

  const getData = useCallback(async () => {
    const config = {
      headers: {
        Authorization: `token ` + localStorage.getItem("token"),
      },
    };
    const res = await axios.get(
      "messages/get-all-messages/?receiver=" + props.id,
      config
    );
undefined which will crash.
    if (res.status === 200) {
      if (mountedRef.current) {
      
        setdata(res.data.);
        
      }
    }
  }, []);

useEffect(() => {
    if (mountedRef.current) {
      getData();
    }
    return function cleanup() {
      mountedRef.current = false;
    };
  }, [getData]);


JSON.parse() does not work on Linux and Mac

I am getting a json response from backend and need to parse the json in frontend.
Here is my code:

this.on("success", function(file, response, action) {
                
                response = JSON.parse(response);      
                console.log(response.id);               
                
            });  

When run the code, it said the following.

 Uncaught SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)

Note: The code do works well on Windows.

How To Solve CORS Error When Trying to Access DHL API

I am trying to integrate DHL API for rate estimate in my website. I am using axios in the frontend to achieve this but i keep getting the CORS POLICY ERROR "Access to XMLHttpRequest at 'https://express.api.dhl.com/mydhlapi/test? from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

I am not using a backend server, hence i can’t get around this error. What should i do in my code to get around this error and get the result back from the API?

here is my code:

const getRateEstimate = () => {

      const options = {
        method: 'GET',
        url: 'https://express.api.dhl.com/mydhlapi/test',
        params: {
          accountNumber: 'myaccnumber',
          originCountryCode: fromCountriesCode,
          originCityName: fromCountriesCapital,
          destinationCountryCode: toCountriesCode,
          destinationCityName: toCountriesCapital,
          weight: weight,
          length: '5',
          width: '5',
          height: '5',
          plannedShippingDate: date,
          isCustomsDeclarable: 'false',
          unitOfMeasurement: 'metric',
          
        },
        headers: {
          Authorization: 'Basic authkey',  


        }
      };
     
        axios.request(options).then((response) => {
            console.log(response.data);
            setData(response.data);
        }).catch((error) => {
            console.error(error);
        });
      }

an example of async/await in javascript

I am studying async and await in javascript, and a little bit confused about the execution order of the following function I wrote when I play around async and await:

const promiseA = new Promise((resolutionFunc, rejectionFunc) => {
  setTimeout(() => resolutionFunc(666), 5000);
});

const test = async () => {
  await promiseA.then((val) =>
    console.log("asynchronous logging has val:", val)
  );
};

const testTwo = () => {
  test();
  console.log("immediate logging");
};

testTwo();

my understand is that in function <testTwo()>, <test()> execute first, it’s been called & executed, <test()> is an async function, and I have put the await in front of the promise.

why this console.log("immediate logging"); line of code get executed first?

on the other hand, if I wrote <testTwo()> like following:

const testTwo = async () => {
  await test();
  console.log("immediate logging");
};

everything is fine

Unable to write and read values in a database, using Discord.js

I’m trying to allow staff to reply to the last DM using ~reply <message> rather than ~dm <userID> <message>, but firstly, I have to save the user’s ID in a database to know who was the last DM user, but I’m facing an ERROR here, I’m confused of why this may be happening, but please note, I’m really new to databases, I’d apricate some help!

My code (Not all, just what I’m using for the command.):

I added “>>” before the line the ERROR is.

client.on('message', async message => {
    
  //Dm checker

  if (message.channel.type === 'dm') {

>>  let lastDM = await db.get(`dm_${message.author.id}`)

    if (lastDM === null) lastDm = `dm_NONE`

    if (message.author.id == client.user.id) return;
    if (message.author.id == '818749579369512978') return message.channel.send("This chat has been Blacklisted by the developer (<@"+ BOT_OWNER +">)");
    const embed1 = new MessageEmbed()
      .setTitle("New message!")
      .setAuthor(`Name: `${message.author.username}` ID: `${message.author.id}` `)
      .setColor("GRAY")
      .setFooter("Dm message")
      .addField("Message:", ````${message.content}````, false);
    const embed2 = new MessageEmbed()
      .setTitle("New reply!")
      .setAuthor(`Name: `${message.author.username}` ID: `${message.author.id}` `)
      .setColor("GRAY")
      .setFooter("Dm reply")
      .addField("Reply:", ````${message.content}````, false);
    if (lastDM === `dm_${message.author.id}`) {
        client.channels.cache.get("920895881656532992").send(`You got a reply!`, embed2)
        console.log(lastDM)
      } else {
        await db.set(`dm_${message.author.id}`).then(
          client.channels.cache.get("920895881656532992").send(`I was DMed!`, embed1),
          console.log(lastDM)
        )
      }
    }

The ERROR:

(node:703) UnhandledPromiseRejectionWarning: SyntaxError: Failed to parse value of dm_612110791683866644, try passing a raw option to get the raw value
    at /home/runner/DwaCraft-Main-bot-Fixed/node_modules/@replit/database/index.js:36:17
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Client.get (/home/runner/DwaCraft-Main-bot-Fixed/node_modules/@replit/database/index.js:20:12)
    at async Client.<anonymous> (/home/runner/DwaCraft-Main-bot-Fixed/main.js:116:18)
(node:703) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)