Javascript code not running as expected

Check out this code snippet:

function generateRandomTeams() {
  const prom = new Promise(() => {
    // ...
    console.log('teams', props.state.teams) // logs
  })
  .then(() => {
    console.log('here') // doesn't log
  })
}

I'm facing an issue where the functions inside .then(() => are not getting executed after the initial block. I haven't included a return statement in the process.

Any suggestions on how I can successfully trigger the delayed promise call? Your help is greatly appreciated.

Answer №1

Make sure to handle the Promise correctly by either resolving or rejecting it. If you do not do either, the promise will remain in a pending state and the corresponding blocks will not be executed.

This image is taken from MDN

https://i.sstatic.net/PbhbY.png

function generateRandomTeams() {
  const prom = new Promise((res, rej) => {
      console.log("teams"); // logs
      res();
    })
    .then(() => {
      console.log("here"); // doesn't log
    })
}

generateRandomTeams();

If you want to run the catch block then you have to reject the Promise

function generateRandomTeams() {
  const prom = new Promise((res, rej) => {
      console.log("teams"); // logs
      rej();
    })
    .then(() => {
      console.log("here"); // doesn't log
    })
    .catch(() => {
      console.log("Error");
    });
}

generateRandomTeams();

Answer №2

To make use of then, you must first resolve the promise.

function createRandomGroups() {
  const prom = new Promise(resolve => {
    // ...
    console.log('teams') // displays
    resolve();
  })
  .then(() => {
    console.log('here') // does not display
  })
}

createRandomGroups();

It's important to note that typically, 'then' is used as follows:

function CreateRandomTeams() {
  return new Promise(resolve => {
    // ...
    console.log('teams') // displays
    setTimeout(() => {resolve()}, 3500);
  });
}

CreateRandomTeams()
.then(() => {
  alert("After 3.5 seconds: Then executed");
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying the state in NextJS rather than revealing server error messages

I recently implemented a register page on my NextJS app where users can input their information. Once the registration is successful, the form clears and a success message is displayed. However, I encountered an issue after adding the success message. Now ...

Troubleshooting: Issues with AngularJS $route.reload() functionality

I have an angular app and I'm attempting to refresh the page. I've tried using $route.reload() as recommended in multiple posts, but I can't seem to get it to work (Chrome is showing me an error). Here's my controller: var app = angula ...

How can you create a jQuery fade in effect for a single <li> element

I'm in the process of developing a task management app that generates a new li element every time a user adds an item. However, I am facing an issue where fadeIn() is activating for every li on the page whenever a new item is added. Does anyone have s ...

The JSON creation response is not meeting the expected criteria

Hello, I'm currently working on generating JSON data and need assistance with the following code snippet: generateArray(array) { var map = {}; for(var i = 0; i < array.length; i++){ var obj = array[i]; var items = obj.items; ...

How can I make my Background change on click using hexadecimal color codes?

I am struggling with changing the background color of an html document using a button click. While colors like "yellow, "blue", and "red" work perfectly, I encounter an issue when trying to use hexadecimal colors such as "#000000". The if-condition doesn ...

Is there a way to deactivate or dim a specific hour in an HTML time form?

I am currently facing a challenge with my booking form. I need to find a way to grey-out or disable the hours/times that have already been booked by previous customers. This will help ensure that the next person can select a different time slot. However, I ...

AngularJs - Show the response only upon verifying the correct answer

Let me provide an overview of what has been implemented so far: When a user selects an answer in radio buttons and clicks on "Check Answer", the system displays either "Correct" (in green) or "Incorrect" (in red) in the first answer field. Additionally, th ...

Can a wasm file be registered in a similar way to a JavaScript file?

My JavaScript file is calling a WebAssembly (wasm) file, but it is fetching the file from the wrong location when I register the script in a specific part of the code. To address this issue, what is considered the best practice? Here's the current s ...

The onClick function within the .map function is continuously triggered

I am encountering an issue with my code where a Dialog confirmation prompt from Material UI keeps getting called unexpectedly. The problem seems to arise when I add a value to the function that is triggered by a button click within a loop of an array usi ...

What is the best way to troubleshoot an unresponsive button element to determine the listeners it has?

In a previous situation, I encountered an issue with the event modifier of a nested b-input not working as expected. To resolve this, I had to add .native because I was interacting with a component: b-dropdown(text="Actions") b-drop ...

Sharing properties across various components with Next.js

I'm still getting the hang of using Next.js and encountering issues with sharing data between components. Currently, I have a setup involving three components: //index.js function App() { const choices = [] for (let i = 1; i < 101; i++) { ...

Prevented a frame from "https://googleads.g.doubleclick.net" from accessing another frame

After placing ads on my website, they are displaying properly. However, I am receiving an error repeatedly in the console when the page loads: A frame from origin "" is being blocked from accessing a frame with origin "". The requesting frame has an "ht ...

Implementing objects in a three.js scene without displaying them on the screen

I have a function called createCylinder(n, len, rad) that is being invoked from another function named createScene(). Despite checking that the vertices and faces are correctly added without errors, the geometry itself is not rendering. I suspect this is ...

What is the process of turning an SVG element into a clickable link?

Is there a way to transform each element within an SVG image embedded in an HTML file into an active link? I want to create an SVG image with clickable elements. Here is a snippet of the SVG image: <svg version="1.1" id="Layer_1" xmlns="http://www.w3 ...

What is the method to showcase every single word?

Can someone help me with my assignment? I am tasked with creating a small user interface that searches a list of words using HTML, CSS, and Javascript. The design is provided, but I need to implement it. I have written the code, but I would like all wor ...

Endless Google Locations Instances

My database entries are being displayed in a table using input fields. I want the Location field for each entry to be automatically completed using Google's API. HTML: <input name="edit_airplane[1][location]" type="text" class="airplane_location" ...

Tips for troubleshooting the error message "is not a function" in a React application

Hi there, I'm currently delving into learning React and have encountered an issue that says: (TypeError: newsData.map is not a function) in my browser when running my code. Oddly enough, Visual Studio Code doesn't flag any errors, only Chrome doe ...

Is it possible to scroll by using the dragenter event?

Looking for a way to achieve incremental scroll up and scroll down using jQuery without jQuery UI? Here's the scenario - I have two divs: <div class="upper" style="height:35px;background-color:red;right:0;left:0;top:0;position:fixed;width:100%;z-i ...

Axios is experiencing challenges in transmitting the cookie

Even after attempting to include {withCredentials: true}, I am still facing issues with sending the cookie to the backend server. return await axios.post(`${API_URL}/posts/category/${id}`, { withCredentials: true }) https://i.stack.imgur.com/Cr8xv.png ...

React app experiencing freezing due to custom asynchronous function utilisation

I am currently facing an issue with my personal project where the application freezes under certain circumstances. The initial load works fine, but when I make changes to the code causing React to re-render, the app just freezes. It seems to be related to ...