What await does exactly and does it have anything to do with microtask queue?

I am new to JavaScript and I am trying to understand what await does and what is its relation with microtask queue. The following code is just for clarification purpose only.

async function afunc() {
  console.log("a1");
  const b = bfunc();
  console.log("a2");
  b.then((value) => {
    console.log(value);
  });
  return "a value";
}

async function bfunc() {
  console.log("b1");
  await console.log("waiting");
  console.log("b2");
  return "b value";
}

const a = afunc();

a.then((value) => {
  console.log(value);
});

console.log("script end");

And the results are:

a1
b1
waiting
a2
script end
b2
a value
b value

On MDN it says

The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment.

When does this ‘resume’ happen exactly? And does it has anything relatable to microtask queue in terms of execution order?

Also, I expect b value to show up before a value since it seems that b.then() will be pushed in microtask queue before a.then() is, and the actual output confused me a lot.

Any help would be much appreciated!

Best approach to retrieve live data from Arduino to server

I have a small arduino program that collects data through sensors. I am able to POST this data each second to an API endpoint so the data can be seen in real time. However, I am concerned this approach might not be the best way to get real-time data.

First, I only need to POST data to the server when a client connection actually exists (i.e an observer on the front-end).

Second, even if there is a client connection, my code sends http requests every second and I am worried this might become too heavy for the server to handle especially if there are multiple devices posting data to the server.

I was wondering what is the best approach to solve this problem efficiently?
Thank you,
Mehdi

How to open a file in folders with discord.js

I am now coding a Discord bot in a folder named “bot”, and I am making it play audio file. But I face a problem. If every files I want to make it play are stored in “bot”, the folder will look mess. So I want to create a new folder named “music” in “bot”. But I don’t know to open the file in this way. Here is a part of my original code:

if (cmd === "play" && message.member.voice.channel) {
        const connection = await message.member.voice.channel.join();
        const dispatcher = connection.play('01. Snow halation.flac');
        dispatcher.on('start', () => {
            console.log('Now playing!');
        });
        dispatcher.on('finish', () => {
            console.log('Finished playing!');
            connection.disconnect();
        });
        dispatcher.on('error', console.error);

I want let file “01. Snow halation.flac” be in “music”, and how can I make it play?

getting a document from firestore, in a method that returns undefined [duplicate]

so, i’m trying to get a single document from a collection, using the id from the current user, the request [getDoc] works, but when i’m trying to return the information from the exported function is where i’, having all the problems, the function is called but it acts before the function returns the values it needs, so it only gets undefined information, i’ve tryed with .then(), async functions but it doesn’t work at all

this is on the main javascript file called by the html
<•script type=”module” src=”./Home.js”>

window.addEventListener('DOMContentLoaded', async() => {
    UserStatus()
    
    const userinfo = await getUserInfo('UniversityStaff');
    //.then((userinfo) => {
        console.log(userinfo.data())
    //     const userProfile = userinfo.data();
    //     let html ='';
    //     html+=`
    //     <h5><b>Usuario:</b>${userProfile.userName}</h5>
    //     <h5><b>Correo institucional:</b>${userProfile.email}</h5>
    //     <h5><b>Telefono:</b>${userProfile.phone}</h5>
    //     <h5><b>Departamento:</b>${userProfile.area}</h5>
    //     <h5><b>Puesto:</b>${userProfile.jobTitle}</h5>
    //     <h5><b>Horario:</b>${userProfile.workingHours}</h5>`
    
    //     userInfo.innerHTML = html;
    // })
    })

this is the javascript file that contains all the code from the firebase modules.
this is imported by the ./Home.js

export const getUserInfo = (collection) => {
       onAuthStateChanged(auth, (user) => {
        if (user) {
          getDoc(doc(db, collection, user.uid))
          .then((doc)=>{
            console.log(doc.data())
            return doc;

          })
        }
      })
    }

•this is the error from the [.then()/await] getting done before the [export const getUserInfo]


Home.js:14 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘data’)
at Home.js:14:30
(anonymous) @ Home.js:14



•this is the data from the request on [export const getUserInfo]


firebase.js:112 {area: ”, id: ‘jX3J5XjwDphlE1rQRxlxOHyDqMI2’, email: ‘[email protected]’, phone: ‘6181690397’, userName: ‘Edmundo Gurrola’, …}

Is there any way to embed a youtube playlist in a html website, but have each video listed separately?

Basically, I am trying to embed youtube playlists onto my website, but I would like to have each video be separate (kind of like the youtube homepage). Obviously, I could go through and add each video one by one, but that takes too long for my projects, and making changes in the future would be a nightmare. I have tried looking online but all I could find were widget creators which are not entirely free. If you have any suggestions please let me know, thanks!

Floating Widget like Messenger on Google Site

Hi I am trying to make a floating widget like facebook messenger in google site but the problem is that it only stays at the very bottom on its section

here’s my code

<html>
<style>
.UtePc #pingpilot{
  display: none;
  position: absolute;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  font-size: 18px;
  border: none;
  outline: none;
  background-color: #660000;
  color: white;
  cursor: pointer;
  padding: 15px;
  border-radius: 4px;
}
</style>
<body>
<script id="pingpilot" type="text/javascript" src="https://widget.pingpilot.com/widget-button.js" data-signal="483c60" async></script>
</body>
<html>

enter image description here

When I scroll down to the very bottom it only stays there. What I want is that even if I scroll up it should still float where ever I scroll.

make useEffect run before render is completed

I have functions that I want to execute when state changes. But I don’t want them to wait until render is completed, since it doesn’t depend on the rendered DOM.

Is there a way to execute a function when certain dependencies change just like useEffect, but not wait until rendering is completed?

I was thinking to use useMemo or useCallback, but it seems not an ideal solution since it uses memory.

Is there a direct solution for this?

nested iframe message passing “jumping” over containing iframe

The behavior I’m seeing is really odd and every reference I find online seems to imply it doesn’t work like this, but I haven’t had to do this very much so I need a sanity check on whether this can happen under normal circumstances.

Suppose three pages

  • root page
  • iframe A inside root page (same origin)
  • iframe B inside iframe A (third-party origin)

Here’s the whacky situation I find myself in:

  1. iframe A is listening to messages from iframeB using window.addEventListener('message', ...)
  2. iframe B sends a message
  3. iframe A does not receive the message
  4. if a message listener is added to root page, it does receive the message

So my question is as follows: What?

fetch request does not run javascript

I am making a fetch request to a website on google web cache. Here is the url: https://webcache.googleusercontent.com/search?q=cache:fpiE2WZCmacJ:https://www.bloomberg.com/news/articles/2022-07-18/russian-gas-supply-halt-risks-1-5-cut-to-eu-s-gdp-in-worst-case+&cd=1&hl=en&ct=clnk&gl=us&client=safari#xj4y7vzkg (The link works on chrome but has bugs on safari.)

When I go to the link the page first has the basic content with the article covered like this: enter image description here

Then, the javascript runs and you can see the full article.

The problem is when I made a postman get request, I then created an index.html file and pasted in the html and opened the file. The website stays stuck like this: enter image description here.

I was wondering since the page html and js is the same as the url, why is the javascript not running and returning the article? Rather it just stays stuck on loading forever. I really appreciate any help.

Error: Cannot find module ‘C:Usersrodrinodejs_paypalsrcindex.js’

I got these errors on terminal:

PS C:Usersrodrinodejs_paypal> npm run dev

[email protected] dev
babel-node src/index.js

node:internal/modules/cjs/loader:936 throw err; ^

Error: Cannot find module ‘C:Usersrodrinodejs_paypalsrcindex.js’
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at Object. (C:Usersrodrinodejs_paypalnode_modules@babelnodelib_babel-node.js:176:21)ejs_paypalnode_modules@babelnodelib_babe/cjs/loader:1105:14)l-node.js:176:21)
ternal/modules/cjs/loader:1159:10)
at Module._compile (node:internal/modules/loader:981:32)/cjs/loader:1105:14)
odules/cjs/loader:822:12)
at Object.Module._extensions..js (node:inMain] (node:internal/modules/run_main:77:12)ternal/modules/cjs/loader:1159:10)
47 {
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47 { code: ‘MODULE_NOT_FOUND’, requireStack: [] } PS
C:Usersrodrinodejs_paypal>

this is my code:

index.js

import express from 'express'

.babelrc

{
    "presets": [
        "@babel/preset-env"
    ]
}

package.json

{
  "name": "nodejs_paypal",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "babel-node src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.27.2",
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "morgan": "^1.10.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.18.9",
    "@babel/core": "^7.18.9",
    "@babel/node": "^7.18.9",
    "@babel/preset-env": "^7.18.9",
    "babel-install": "2.1.0"
  }
}

My index file is here:

enter image description here

How to solve this issue?

Can’t get json data to display

I’m trying to utilize a code snippet that I found here on Stack Overflow posted 9 years ago by Sahan0710 as an answer to another user and I just can’t get the data to display. Even after scouring the alternative solutions for possible missing details.

This is exactly what I need, so if anyone can enlighten me as to what’s wrong or missing or whatever, I would greatly appreciate it. I’m braced to find it’s something ridiculously simple.

<BODY>
<H2>Groceries</H2>
<TABLE ID = "tb1" BORDER = "1">
    <TR>
        <TH>Item</TH>
        <TH>Qty</TH>
        <TH>UoM</TH>
    </TR>
</TABLE>

<SCRIPT type="text/javascript">
    fetch("groceries.json")
        .then(response => response.json())
        .then(data => {
        for (var i = 0; i < data.items.length; i++){
            let vitem = data.records[i].item;
            let vqty = data.records[i].qty;
            let vuom = data.records[i].uom;
            document.querySelector("#tb1").innerHTML += `
                <tr>
                    <td>${vitem}</td>
                    <td>${vqty}</td>
                    <td>${vuom}</td>
                </tr>`;
            }
        })
</SCRIPT>

json file: groceries.json

{
  "records" : [
    {
      "ck" : "",
      "item" : "Cheddar Cheese",
      "qty" : "1",
      "uom" : "lbs",
      "notes" : "Sharp"
    },
    {
      "ck" : "",
      "item" : "Hamburger",
      "qty" : "1",
      "uom" : "Pk",
      "notes" : "80/20"
    },
    {
      "ck" : "x",
      "item" : "Milk",
      "qty" : "3",
      "uom" : "Gal",
      "notes" : ""
    },
    {
      "ck" : "",
      "item" : "Orange Juice",
      "qty" : "2",
      "uom" : "",
      "notes" : ""
    }
  ]
}

Creating a custom Hook that includes useRef

In the following code I create a hook that uses useState inside it, the hook works perfectly. Then I create a second custom hook that inside uses a useRef to print an html element in the console, the latter doesn’t work because I don’t know how to refer to the element from the hook I’m creating. Here the code:

import "./styles.css";
import {useEffect, useRef, useState} from "react"

function useChangeText(){
  const [n,setN]= useState(0)
  const sum= ()=> setN(n + 1)
  return {number:n,sum}
}

function useGetHTML(n){
  const element= useRef(null)
  useEffect(()=>{
    console.log(element.current)
  },[n])
}

export default function App() {
const hookSum= useChangeText()
const element= useGetHTML(hookSum.number)

  return (
    <div ref={element} className="App">
      <h1>{hookSum.number}</h1>
      <button onClick={hookSum.sum}>click +1</button>
    </div>
  );
}

How do I get my code on google sheets to cover multiple tabs?

I have a code that runs on my google sheets every time someone fills out a form online which pushes info into my CRM Software. It pulls the info in great off of the main tab; but how can I get the script to run for multiple tabs on the same spreadsheet? I tried a couple solutions but couldn’t figure it out. this is the current code

var sheet = SpreadsheetApp.getActiveSheet();

var scriptProperties = PropertiesService.getScriptProperties();   
var lastRange = scriptProperties.getProperty("last_range");

//Logger.log("Debug:" + lastRange);

if (!lastRange) {
  var lastRow = sheet.getDataRange().getLastRow() + 1;
  scriptProperties.setProperty("last_range", "A" + lastRow);
  lastRange = scriptProperties.getProperty("last_range");
}

var range = sheet.getRange(lastRange);
var totalRange = sheet.getDataRange();
var isBlank = range.isBlank();
var isGreater = false;