NODEjs: TypeError: The “password” argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView. Received undefined

I keep getting this error in my terminal when I run my app but I do not have a password variable anywhere in my code

TypeError: The "password" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView. Received undefined
    at check (node:internal/crypto/scrypt:89:14)
    at Object.scryptSync (node:internal/crypto/scrypt:70:13)
    at Object.<anonymous> (/Users/gokeadewuyi/abc/algorand/node_modules/@african-blockchain-center/common/build/utils/encryption.js:8:30)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._compile (/Users/gokeadewuyi/abc/algorand/node_modules/source-map-support/source-map-support.js:568:25)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at require.extensions..jsx.require.extensions..js (/private/var/folders/7m/t45z59v16x51rby86nhtvx2m0000gn/T/ts-node-dev-hook-9974711466048651.js:114:20)
    at Object.nodeDevHook [as .js] (/Users/gokeadewuyi/abc/algorand/node_modules/ts-node-dev/lib/hook.js:63:13)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Function.Module._load (node:internal/modules/cjs/loader:922:12)

this is my app.ts file

import express from "express";
import "express-async-errors";
import { json } from "body-parser";
import cookieSession from "cookie-session";
import {
  errorHandler,
  NotFoundError,
  currentUser,
} from "@african-blockchain-center/common";

const app = express();
app.set("trust proxy", true);
app.use(json());
app.use(
  cookieSession({
    signed: false,
    secure: true,
  })
);
app.use(currentUser);

app.all("*", async (req, res) => {
  throw new NotFoundError();
});

app.use(errorHandler);

export { app };

and my index.ts file


import { app } from "./app";

const start = async () => {
  if (!process.env.JWT_KEY) {
    throw new Error("JWT_KEY must be defined");
  }
 

  app.listen(3000, () => {
    console.log("algorand-service reporting for duty!");
  });
};

start();

I have been debugging for several hour but can’t solve the issue, I have checked the imported node modules for the “password” variable but could not find it as well

Calling Javascript from C# ASP.NET Core

I am using SignalR within an ASP.NET core application but rather than creating the connection and sending/receiving of messages in Javascript I’m trying to do that in C#. So my application can connect to the SignalR hub and sends messages and receives messages. So I’m now wanting to update the UI with the messages to be broadcast. In the connection.On method I am using the following line of code to try to call a Javascript function to display the new message:

await _jsRuntime.InvokeVoidAsync("updateUI", $"{user}: {message}");

having injected IJSRunTime into my class (updateUI is a Javascript method on the page to update the UI with the new message). The code runs, however, the Javascript function is not being called (I’ve added a console.log message to confirm that). I’m not using Blazor because I’m trying to have a general service that can be used from both ASP.NET and React.

Any help on how to call Javascript from ASP.NET C# would be appreciated.

Tried a range of measures such as checking the network log putting alart/console.log messages into the function. From the call to InvokeVoidAsync, I expected the named Javascript function to be called.

TypeError: d3.map(nodes, nodeId).map is not a function

I am trying to run the example force-graph here with the miserables dataset. However, when I try to run the example I get the following error:

TypeError: d3.map(nodes, nodeId).map is not a function. (In 'd3.map(nodes, nodeId).map(intern)', 'd3.map(nodes, nodeId).map' is undefined)

This is the code I’m using directly from the website. I have not changed anything except for commenting out the invalidation parameter. I was not sure what to set this to, which is why I removed the option.

 function ForceGraph({
    nodes, // an iterable of node objects (typically [{id}, …])
    links // an iterable of link objects (typically [{source, target}, …])
  }, {
    nodeId = d => d.id, // given d in nodes, returns a unique identifier (string)
    nodeGroup, // given d in nodes, returns an (ordinal) value for color
    nodeGroups, // an array of ordinal values representing the node groups
    nodeTitle, // given d in nodes, a title string
    nodeFill = "currentColor", // node stroke fill (if not using a group color encoding)
    nodeStroke = "#fff", // node stroke color
    nodeStrokeWidth = 1.5, // node stroke width, in pixels
    nodeStrokeOpacity = 1, // node stroke opacity
    nodeRadius = 5, // node radius, in pixels
    nodeStrength,
    linkSource = ({source}) => source, // given d in links, returns a node identifier string
    linkTarget = ({target}) => target, // given d in links, returns a node identifier string
    linkStroke = "#999", // link stroke color
    linkStrokeOpacity = 0.6, // link stroke opacity
    linkStrokeWidth = 1.5, // given d in links, returns a stroke width in pixels
    linkStrokeLinecap = "round", // link stroke linecap
    linkStrength,
    colors = d3.schemeTableau10, // an array of color strings, for the node groups
    width = 640, // outer width, in pixels
    height = 400
    ///, // outer height, in pixels
    ///invalidation // when this promise resolves, stop the simulation
  } = {}) {
    // Compute values.
      const N = d3.map(nodes, nodeId).map(intern);
      const LS = d3.map(links, linkSource).map(intern);
      const LT = d3.map(links, linkTarget).map(intern);
      if (nodeTitle === undefined) nodeTitle = (_, i) => N[i];
      const T = nodeTitle == null ? null : d3.map(nodes, nodeTitle);
      const G = nodeGroup == null ? null : d3.map(nodes, nodeGroup).map(intern);
      const W = typeof linkStrokeWidth !== "function" ? null : d3.map(links, linkStrokeWidth);
      const L = typeof linkStroke !== "function" ? null : d3.map(links, linkStroke);
    
      // Replace the input nodes and links with mutable objects for the simulation.
      nodes = d3.map(nodes, (_, i) => ({id: N[i]}));
      links = d3.map(links, (_, i) => ({source: LS[i], target: LT[i]}));
    
      // Compute default domains.
      if (G && nodeGroups === undefined) nodeGroups = d3.sort(G);
    
      // Construct the scales.
      const color = nodeGroup == null ? null : d3.scaleOrdinal(nodeGroups, colors);
    
      // Construct the forces.
      const forceNode = d3.forceManyBody();
      const forceLink = d3.forceLink(links).id(({index: i}) => N[i]);
      if (nodeStrength !== undefined) forceNode.strength(nodeStrength);
      if (linkStrength !== undefined) forceLink.strength(linkStrength);
    
      const simulation = d3.forceSimulation(nodes)
          .force("link", forceLink)
          .force("charge", forceNode)
          .force("center",  d3.forceCenter())
          .on("tick", ticked);
    
      const svg = d3.create("svg")
          .attr("width", width)
          .attr("height", height)
          .attr("viewBox", [-width / 2, -height / 2, width, height])
          .attr("style", "max-width: 100%; height: auto; height: intrinsic;");
    
      const link = svg.append("g")
          .attr("stroke", typeof linkStroke !== "function" ? linkStroke : null)
          .attr("stroke-opacity", linkStrokeOpacity)
          .attr("stroke-width", typeof linkStrokeWidth !== "function" ? linkStrokeWidth : null)
          .attr("stroke-linecap", linkStrokeLinecap)
        .selectAll("line")
        .data(links)
        .join("line");
    
      const node = svg.append("g")
          .attr("fill", nodeFill)
          .attr("stroke", nodeStroke)
          .attr("stroke-opacity", nodeStrokeOpacity)
          .attr("stroke-width", nodeStrokeWidth)
        .selectAll("circle")
        .data(nodes)
        .join("circle")
          .attr("r", nodeRadius)
          .call(drag(simulation));
    
      if (W) link.attr("stroke-width", ({index: i}) => W[i]);
      if (L) link.attr("stroke", ({index: i}) => L[i]);
      if (G) node.attr("fill", ({index: i}) => color(G[i]));
      if (T) node.append("title").text(({index: i}) => T[i]);
      ///if (invalidation != null) invalidation.then(() => simulation.stop());
    
      function intern(value) {
        return value !== null && typeof value === "object" ? value.valueOf() : value;
      }
    
      function ticked() {
        link
          .attr("x1", d => d.source.x)
          .attr("y1", d => d.source.y)
          .attr("x2", d => d.target.x)
          .attr("y2", d => d.target.y);
    
        node
          .attr("cx", d => d.x)
          .attr("cy", d => d.y);
      }
    
      function drag(simulation) {    
        function dragstarted(event) {
          if (!event.active) simulation.alphaTarget(0.3).restart();
          event.subject.fx = event.subject.x;
          event.subject.fy = event.subject.y;
        }
        
        function dragged(event) {
          event.subject.fx = event.x;
          event.subject.fy = event.y;
        }
        
        function dragended(event) {
          if (!event.active) simulation.alphaTarget(0);
          event.subject.fx = null;
          event.subject.fy = null;
        }
        
        return d3.drag()
          .on("start", dragstarted)
          .on("drag", dragged)
          .on("end", dragended);
      }
  
    return Object.assign(svg.node(), {scales: {color}});
  }

  ForceGraph(network_data, {
    nodeId: d => d.id,
    nodeGroup: d => d.group,
    nodeTitle: d => `${d.id}n${d.group}`,
    linkStrokeWidth: l => Math.sqrt(l.value),
    width: 600,
    height: 600
    ///,
    ///invalidation // a promise to stop the simulation when the cell is re-run
  })

Any help is much appreciated. Thanks for reading.

how to get the relative rotation in degrees even after its passed 360 degrees

if i have a circle that rotates, and reach’s twice round 360 i would get 720 degrees, but when i rotate to 360 or 720 the result would give me 0 degrees but i need the relative degrees so if the circle rotates to 360 the result should be 360 not 0. Is there a formula or functionality to get the exact rotation after its passed 359 degrees.

When i use this:

$("#round-play1")[0].style.transform = `rotate(${810}deg)`;

The result when retrieving the degrees would give me 90 degrees, but i need to get 810 degrees not 90 degrees.

I tried this:

function getCurrentRotation(el){
        var st = window.getComputedStyle(el, null);
        var tm = st.getPropertyValue("-webkit-transform") ||
                st.getPropertyValue("-moz-transform") ||
                st.getPropertyValue("-ms-transform") ||
                st.getPropertyValue("-o-transform") ||
                st.getPropertyValue("transform") ||
                "none";
        if (tm != "none") {
        var values = tm.split('(')[1].split(')')[0].split(',');
        var angle = Math.round(Math.atan2(values[1],values[0]) * (180/Math.PI));
        return (angle < 0 ? angle + 360 : angle); //adding 360 degrees here when angle < 0 is equivalent to adding (2 * Math.PI) radians before
        }
        return 0;
    }

But would not give me the exact relative degrees.

How to retrieve a php information inide a javascrip

Inside my product.php code I have a loop

            <?php
              for ($i = 0, $n = count($languages); $i < $n; $i++) {
            ?>
                    <div class="row" id="seoDefaultTitleH<?php echo $languages[$i]['id']; ?>">
                      <div class="col-md-10">
                        <div class="form-group row" data-index="<?php echo $languages[$i]['id']; ?>">
                          <label for="<?php echo $SEO->getDef('text_seo_defaut_language_title_h1'); ?>" class="col-5 col-form-label"><?php echo $SEO->getDef('text_seo_defaut_language_title_h1'); ?></label>
                          <div class="col-md-7 input-group" id="seo_default_title_h<?php echo $languages[$i]['id']; ?>">
                            <?php echo '&nbsp;' . HTML::inputField('seo_defaut_language_title_h1_[' . $languages[$i]['id'] . ']', ($seo_defaut_language_title[$languages[$i]['id']] ?? SeoAdmin::getSeoTitleH1($seo->seo_id, $languages[$i]['id'])), 'maxlength="70" size="77" id="seo_default_title_h_' . $languages[$i]['id'] . '"', false); ?>
                          </div>
                        </div>
                      </div>
                    </div>
<?php
}
?>

Inside my script.php I have these elements

As you inside my js I need to take a php function to retrieve the good language. But I do not find How to do that allowing the php function to be operationnal.

Thank you.

let language_name = '{$Language->getLanguagesName(' + language_id + ')}';

all the code


   $Language = Registry::get('Language');

   $content = '<button type="button" class="btn btn-primary btn-sm submit-button" data-index="0">';
   $content .= '<i class="bi-chat-square-dots" title="' . $this->app->getDef('text_seo_page_title') . '"></i>';
   $content .= '</button>';

$output = <<<EOD
<script defer>
$('[id^="seo_default_title_h"]').each(function(index) {
  let button = '{$content}';
  let newButton = $(button).attr('data-index', index);
  let inputId = $(this).attr('id'); 
  let regex = /(d+)/g; 
  let idSeoDefaultTitleH = regex.exec(inputId)[0];
 


//  here the problem to retrieve language_id
  let language_id = parseInt(idSeoDefaultTitleH); //ok
  let language_name = '{$Language->getLanguagesName(' + language_id + ')}'; // no ok



  let questionResponse = '{$question_title}' + ' ' + '{$store_name}' + ' : traduction ' +  language_name 
  
  newButton.click(function() {
    let message = questionResponse;

    $.post("{$url}", {message: message}, function(data) {
      $("#output-input").val(data);
      $("#seo_default_title_h_" + idSeoDefaultTitleH).val(data); 
    });
  });

  $(this).append(newButton); 
});
</script>

EOD;
      return $output;

Evaluating file properties and API responses in Chai assertions

This is my first time using Chai. I want to write tests that will upload a file and look at the responses. I suspect my code below is close but there might be details I’m not aware of.

  1. Is my file being dynamically created correctly?
  2. How do I extract the filename from testfile?
  3. Am I correctly attaching the file to the Request global?
const chai = require('chai');
const expect = chai.expect;
const COUNT_API_URL = 'http://localhost:8080/api/fileUpload';

// mock file
class MockFile {
    constructor ({ name = 'file.txt', size = 1024, type = 'plain/txt', lastModified = new Date() }) { }
    create (name, size, mimeType) {
        const blob = new Blob([ 'a'.repeat(size) ], { type });
        blob.lastModifiedDate = lastModified;
        return new Blob([ blob ], name);
    }
}

describe('file-upload-api', () => {
    // mock file test harness
    describe('Mock file for file upload testing', () => {
        const testfile = new MockFile({
            type: 'image/png',
            size: 50000,
            name: 'helloworld.txt',
        });

        it('testfile should be defined', () => {
            expect(testfile).to.not.be.undefined;
            expect(testfile.name).to.equal('helloworld.txt');
            expect(testfile.size).to.equal(50000);
        });

        it('should return 200 when a valid file is uploaded', async () => {
            const request = new Request(COUNT_API_URL, { method: 'POST', body: { files: [ testfile ] } });
            return await fetch(request)
                .then((response) => response.json())
                .then((data) => {
                    expect(data).to.eql({ message: 'request.file.originalname: helloworld.txt' });
                });
        });

        it('should return 400 when a null file is uploaded', async () => {
            const request = new Request(COUNT_API_URL, { method: 'POST', body: { files: [] } });
            return await fetch(request)
                .then((response) => response.json())
                .then((data) => {
                    expect(data).to.eql({ message: 'Please upload a file' });
                });
        });

    });

});

I am making a react native chat app and can’t figure out how to limit the length of the chat bubble before wrapping it to a new line

I am making a chat app with React Native using TS and NativeWind. I am trying to make the chat bubble’s wrap after a certain length but whenever I put a fixed width on the chat bubble it always colors the whole width of the bubble, even if it isn’t fill out.

enter image description here

Here you can see even if I don’t use the whole length of the chat bubble the bubble is filled orange.
I want the bubble to only be as big as it needs to fit the user content & email but wrap the text after I certain length.

import { View, Text } from "react-native";
import { Avatar, Divider } from "react-native-paper";
import { COLORS } from "../../constants";
import { styled } from "nativewind";

const StyledDivier = styled(Divider);

type Props = {
  text: string;
  email: string;
  date: string;
  time: string;
};

function UserSent({ text, email, date, time }: Props) {
  return (
    <View className="flex flex-row items-start justify-end w-full py-4 space-x-2 ">
      <View className="flex flex-col   space-y-1 pt-1 ">
        <Text className="text-xs text-foxGray">{date}</Text>
        <Text className="text-xs text-foxGray">{time}</Text>
      </View>

      <View className="flex flex-row">
        <View className=" p-2 rounded-md bg-foxOrange mr-2 w-60">
          <Text className="text-sm text-foxGray text-right ">{email}</Text>
          <StyledDivier className=" bg-foxGray" />
          <Text className="text-foxWhite pt-2 text-right ">{text}</Text>
        </View>

        <Avatar.Icon
          size={40}
          icon="account"
          color={COLORS.light.foxWhite}
          style={{ backgroundColor: COLORS.light.foxOrange }}
        />
      </View>
    </View>
  );
}

export default UserSent;

Can someone help me change or rewrite my code so the bubble only takes up as much space as it needs but wraps after it reaches a certain length.
enter image description here

How to modify a global variable

const searchbtn = document.getElementById('Search-btn');
const cityinput = document.getElementById('city-input');
const apiKey = 'key';
let lon;
let lat;

function GeoGet() {
    let GeoApiUrl = `http://api.openweathermap.org/geo/1.0/direct?q=${cityinput.value}&limit=1&appid=${apiKey}`
    fetch(GeoApiUrl)
        .then(response => response.json())
        .then(data => {
           lon = data[0].lon;
            lat = data[0].lat;
            console.log(lon)
            console.log(lat)
        })
        .catch(error => {
            console.error();
        });
}
searchbtn.onclick = () => {
    GeoGet();
    console.log(lon);
    console.log(lon);
}

I want to change the lon and lat in the function, but it does not work.
I can’t understand why

Console

open vuetify v-dialog component using js instead of html

I’m using vue3 and vuetify framework, and trying to open a dialog when press a button. vuetify needs to inject “v-dialog” nodes in each html pages, instead I prefer using buefy’s approach , like this.$buefy.dialog.confirm({}) in javascript to trigger dialog, which makes the code more flexible.

how can i do that?

I want to trigger dialog using javascript rather than add nodes in html

Why does `window.location.search` not match `window.location`’s `search` field?

I have logged out the following window.location in my React app (using Google Chrome):

{
    "ancestorOrigins": {},
    "href": "http://localhost:3000/my-path?foo=bar",
    "origin": "http://localhost:3000",
    "protocol": "http:",
    "host": "localhost:3000",
    "hostname": "localhost",
    "port": "3000",
    "pathname": "/my-path",
    "search": "?foo=bar",
    "hash": ""
}

However, logging out window.location.search in the console (on the next line) shows that it’s an empty string: "". This seems to contradict the search field on the window.location object. Here are my logs:

console.log("location", window.location); // search: "?foo=bar"
console.log("search", window.location.search); // ""

Furthermore, both (a) a simple 1 second timeout inside a React.useEffect and (b) a page reload each result in the window.location.search logging out to be "?foo=bar" as expected.

I expected window.location.search to match the search field on the window.location object, but it doesn’t. I suspect some sort of race condition, but I don’t understand the mismatch between window.location and window.location.search

Centering title in the middle of the screen regardless of the size of other elements in the container [duplicate]

I’ve been trying to get my title to stay in the center of the screen regardless of screen size / other elements. I have it in a flexbox with space-between as the content justification. The title always sits a little bit off center because of the size of my links.

How would I get it to stay in the center at all times? I’ve seen some uses of <ul> and I have experimented with the z-position CSS attribute with no luck. I have also experimented with other flex justifications, as well as adjusting the width of the div holding the title (not present in the demo) with no luck. The elements on the left and the right need to be at opposite ends of the screen. This is also in a react project, the fiddle is just an example.

div {
  display: flex;
  flex-direction: row;
  width: 100vw;
  color: red;
  justify-content: space-between;
}
<div className="navbar">
  <h3>
    Links Links Links Links
  </h3>
  <h1>
    Title
  </h1>
  <h2>
    tiny
  </h2>
</div>

How to pass the localStorage values to a usestate variable and updating with useEffects

My project ideea: i want to randomly generate a noun from a js file and when I press a button, that noun to be saved in localStorage(i save all the array, just change that noun property from isFavorite=false to isFavorite=true). In another page, i want to display all the saved nouns.
I have 2 pages: NewNouns and FavoriteWords.
In the NewNouns page I added an array of Objects (this array contains more nouns with some properties). Also, in this page i updated the objects array when I press a button to change the isFavorite value from false to true.

In the FavoriteWords page I have a usestate that receives the values from the localStorage. I displayed on the screen all the nouns with the isFavorite property=true. I want to add to these nouns the possibility to be deleted when I press a button.

My problem is: I don’t know why my usestate from FavoriteWords page doesn’t receive the values from the localStorage (this problem appears just when I use the useEffects to update the deleted nouns). If I don’t use useEffect, everything works ok. But I need useEffect because my components have to re-render when I’m deleting a noun.

—-Example of Object Array —-

export default [{"id":0,"value":"Diamond","translation":"Diamant","isFavorite":false,"appeard":false},
                 {"id":1,"value":" Manager","translation":" Manager","isFavorite":false,"appeard":false},
                 {"id":2,"value":" Area","translation":" Zona","isFavorite":false,"appeard":false}
                ]

—-NewNouns Page—-

import arrayNounsData from '../../Datas/nouns'

const NewNouns = () => {
  const[word,setWord]=React.useState(arrayNounsData.sort(() => 0.5 - Math.random())[0])//the noun displayed
  const[words,setWords]=React.useState(()=>JSON.parse(localStorage.getItem("nouns")) || arrayNounsData) //the Objects array
 
  
  function addToFavorite(){ 
    setWords(prevValue=>prevValue.map(wordData =>{
      return wordData.id === word.id ?
      {
        ...wordData,
        isFavorite: !wordData.isFavorite
      }
      : {...wordData  }})) 
  }
 
  React.useEffect(()=>{
    localStorage.setItem("nouns", JSON.stringify(words))
  },[words])
  
  return ( 
    <>
        {....}
    </>
  )
}

—-FavoriteWords Page—-

const FavoriteWords = () => {
    const [words,setWords]=React.useState(() => JSON.parse(localStorage.getItem(nouns)) || []) //all the array from NewNouns page
    const [favoriteWords, setFavoriteWords]=React.useState(words.filter(word => word.isFavorite === true))//extract just the savedNouns

    const word=favoriteWords.map(word =>(
      <Word
        key={word.id}
        id={word.id}
        word={word.value}
        deleteFromFavorite={deleteFromFavorite}
      />
    ) )

    function deleteFromFavorite(wordId){ 
      setFavoriteWords(prevValue=>prevValue.map(wordData =>{
        return wordData.id === wordId ?
        {
          ...wordData,
          isFavorite:false
        }
        : {...wordData  }}))
      setDeleteWords(prevValue=>prevValue.map(wordData =>{
        return wordData.id === wordId ?
        {
          ...wordData,
          isFavorite: false
        }
        : {...wordData  }}))
    }
   /* React.useEffect(()=>{
      localStorage.setItem("notes" , JSON.stringify(words))
    }, [words])
   */

  return (
    <WordsContainer >
          {word}
    </WordsContainer>
  )
}
export default FavoriteWords

const Word = (props) => {
  return (
      <SelectedContainer >
          {props.word}
          <TrashIcon src={Trash} onClick={() => props.deleteFromFavorite(props.id)} />
      </SelectedContainer> 
  )
}

I used the useEffect hook to re render the components to update the displayed nouns. The problem is that when I use it, the ‘words’ useState (from FavoriteWords page) it’s initialized with [], and not with localStorage values. I don’t know why. How the useEffect works in this case?

I’m having a problem using javascript logic to change the color of column 1 and row 1 to blue in my multiplication table

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiplication Table</title>
    <style type="text/css">
        table,th,td{
            border: 2px solid black;
            border-collapse: collapse; 
        }
        td{
            width: 250px; 
            font-size: 30px

        }



    </style>
</head>
<body>
   <table id="mytable"></table>

   <script type ="text/javascript">
    var table=document.getElementById('mytable');
    var output="";
    for(var i=1; i<=10; i++) {
        output+="<tr>";
        for(var j=1; j<=10; j++) {
            
            output+="<td>"+i*j+"</td>";
        }
        output+="</tr>"
    }
    table.innerHTML=output;

   </script>
    
</body>
</html>

The below code is in HTML. I’m using basic javascript code and I’m trying to change the color for row 1 and column 1 numbers from 1-10 to the color blue. It looks like I’m able to render the multiplication number so far, but I am stuck on the logic of changing the colors. I’m assuming you’d have to use an if/else statement.

Should I handle a mongoose connection with .then or .on?

I’m not sure if I should handle a mongoose connection as a promise or event. (Console.log("Successfully connected")

I think they can be used interchangeably, but I’m curious if there are benefits using it as an event with .on compared to handling it as a regular promise. If there are no benefits, I think I’ll continue using what I find more comfortable, and maybe do a bit more research in the performance difference (I know the performance difference is not that significant but it doesn’t hurt to try to use the most optimum method to handle the connection response)