What is causing this code to run immediately upon the addition of Promise logic?

The coding scenario written below was supposed to have two 4-second delays. However, when the code is run, it executes immediately. It seems that there might be a lack of understanding on my part regarding some basic concept, or perhaps there's a hidden error I'm unable to identify.


          function calculatesomething(resolve) {
            console.log("calculating");

            setTimeout(results(resolve,3),4000);
          }

          var answer=0;
          function results(resolve,n) {
            console.log("got results");

            answer=1;
            resolve(answer+n);
          }

          function doingstuff() {
            console.log("starting");

            var promise1 = new Promise(function(resolve) {
              setTimeout(calculatesomething(resolve),4000);
            });

            promise1.then(function(value) {
              console.log("done: "+value);
            });

            console.log("regular execution");
          }

          doingstuff();
        
      

(apologies for the incorrect indenting here. The indentation issues seem to be inconsistent and outside my control.)

Answer №1

One key concept to remember is this:

 setTimeout(calculate(resolve,3),4000);

Instead of directly calling the function and passing the result, you can simply pass a reference to the function:

 setTimeout(calculate, 4000, /*arguments:*/ resolve, 4);

Answer №2

setTimeout requires a callback function as its first parameter. One approach to solve this is by encapsulating your function invocation within an anonymous function, like so:

function calculateTotal(resolve) {
  console.log("calculating");

  setTimeout(function() {
    generateResults(resolve, 3);
  }, 4000)
}

var finalAnswer = 0;

function generateResults(resolve, number) {
  console.log("retrieving results");

  finalAnswer = 1;
  resolve(finalAnswer + number);
}

function performTask() {
  console.log("starting task");

  var promise1 = new Promise(function(resolve) {
    setTimeout(function() {
      calculateTotal(resolve)
    }, 4000);
  });

  promise1.then(function(value) {
    console.log("task completed: " + value);
  });
        
  console.log("normal execution flow");
}

performTask();

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

Issue detected: data exceeds limits (length=3, offset=32, code=BUFFER_OVERRUN, version=abi/5.0.7) within next-js and ethereum

While working on my Ethereum and Next.js project, I encountered an error during the initialization of the project: Error: data out-of-bounds (length=3, offset=32, code=BUFFER_OVERRUN, version=abi/5.0.7) at Logger.makeError (/home/Documents/projects/eth ...

How can Node / Javascript import various modules depending on the intended platform?

Is there a way to specify which modules my app should import based on the target platform in TypeScript? I am interested in importing different implementations of the same interface for a browser and for Node.js. In C++, we have something like: #ifdef wi ...

Discover the magic of TransformToggle and slideToggle in Javascript, HTML, and CSS

Working on a website coding project and ran into an issue. Trying to utilize an img as a link to slideToggle content. It's working, but I'd like the img to rotate 90deg on the first click and -90deg on the second one. Any solutions are greatly ap ...

Setting an Alias for AVA Tests: A Step-by-Step Guide

I need to set up global aliases in my project without using Webpack or Babel. Currently, I am testing with AVA. The npm package module-alias allows me to define aliases in my package.json file. However, when I try to create a basic example following the d ...

Issue encountered while attempting to create entity in jhipster

After executing the creation of an entity in the command line, JHipster successfully generated Java and script files but encountered issues with updating the database. No new table was inserted despite starting MySQL and turning off the application befor ...

How to automatically insert a page break after a certain string in an array using JavaScript

I've created a code that is intended to implement page breaks after a specific number of new lines or words. I have defined an array that indicates where these breaks should occur within my element. In the example provided in my jsFiddle, you can see ...

Using Chartjs to Dynamically Update Data from Database Values

I'm encountering some difficulties while attempting to refresh my Chartjs doughnut chart with data retrieved from my database. Below is the ajax call that I've implemented successfully: $.ajax({ url: "<!--#include virtual="../include/e ...

Instructions on utilizing the transpiled "main.js" file using gulp

As a novice in Angularjs 1.0, I encountered issues with my script and decided to use gulp to compile ec6 to ec5 by implementing the code provided below. The compilation process generated the file main.js. However, I am unsure about how to connect it when l ...

RXJS buffering with intermittent intervals

Situation: I am receiving audio data as an array and need to play it in sequence. The data is coming in continuously, so I am using an observable to handle it. Since the data arrives faster than it can be played, I want to use a buffer to store the data w ...

Utilize filters on a dataset to display specific information

Front-end: const [filters, setFilters] = useState({ type: "", country:"", }); const onChangeFilterType = e => { const workingObject = {...filters}; workingObject.type = e.target.value; setFilters(workingObject); }; ...

show a notification once the maximum number of checkboxes has been selected

I came across this code snippet from a previous question and I'm interested in making some modifications to it so that a message can be displayed after the limit is reached. Would adding a slideToggle to the .checkboxmsg within the function be the mos ...

Adjust transparency according to the information extracted from the AnalyserNode

Currently, I am exploring ways to animate text opacity based on the volume of an audio file. While browsing online, I came across this specific codepen example, which showcases a similar concept. However, as I am relatively new to JavaScript, I find it ch ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

Exploring the properties of individual Vue components on a single page with v-for loop

Struggling to render a Vue component in a Rails app by iterating through an array of data fetched via Ajax. The Slim template (index.html.slim) for the index page includes a custom_form_item component, where items represent custom forms data from Rails and ...

Unable to transfer data successfully from popup to extension.js

I am currently developing a browser extension using Crossrider and I'm facing an issue with sending data from the popup to extension.js Here is my code for the popup: <!DOCTYPE html> <html> <head> <!-- This meta tag is relevant ...

The module named "jquery" has not been loaded in this context: _. Please use require() to load it

As I work on migrating my Javascript files to Typescript, I encountered an issue when trying to use the transpiled javascript file in an HTML page. The error message I received is as follows: https://requirejs.org/docs/errors.html#notloaded at makeError (r ...

Implementing a Push System without using node.JS

I am looking to develop a notification system similar to Facebook's, where notifications appear on the bottom-left side of the screen when someone interacts with your posts, for example. However, my challenge is that I need the server to send real-ti ...

Using backslashes to escape JSON values within a value in Angular

When retrieving JSON data from the backend, I often encounter an issue where the value is set to "key": "\$hello" and it results in an "Unexpected token d". Is there a way in Angular to handle or escape these characters once received from the server? ...

Error occurred in the middle of processing, preventing the headers from being set

I created a custom authentication middleware, but encountered an error. I'm puzzled about what's going wrong because I expected the next() function to resolve the issue? app.use(function(req, res, next){ if(req.user){ res.local ...

Tips for customizing the cursor to avoid it reverting to the conventional scroll cursor when using the middle click

When you wish to navigate by scrolling with the middle mouse button instead of using the scroll wheel, simply middle-click and your cursor will change allowing for easy scrolling on web pages. Even though I am utilizing style="cursor: pointer" and @click. ...