Fulfill a pledge after a function has been run five times

I'm struggling to understand why my promise is not working as expected and how to resolve the issue. Here is the code snippet:

let count = 0;
function onLoad(){

   count++
   console.log(count);
 
   return new Promise((resolve) => {  

      if(count >= 5){
         console.log('Entered if statement and should resolve the promise')
         resolve(); 
      } 

   }); 
}

async function initialize(){
   await onLoad();
   count = 0;
   console.log('Promise Resolved Successfully!')
}

setTimeout(() => onLoad(), 2000);
setTimeout(() => onLoad(), 4000);
setTimeout(() => onLoad(), 5000);
setTimeout(() => onLoad(), 6000);
setTimeout(() => onLoad(), 7000);
setTimeout(() => initialize(), 3000);

The objective is to resolve the promise after the onLoad() function is called 5 times.

Otherwise, it should delay the resolution until then regardless of when the initialize function is invoked...

Note: I'm confused because even though the code reaches the if statement, the promise still doesn't get resolved!?

Note 2: Adding to the confusion, the code works here but fails in the Chrome console and on JSFiddle?????

Answer №1

The function int() does not successfully resolve its call to loaded() because the if statement (loadedNum>=5) evaluates to false just 3 seconds after being invoked, with loadedNum set to 1 at that time. It does not wait for loadedNum to reach a value greater than or equal to 5.

The following code introduces a global Promise's resolver which is triggered whenever loaded() detects that loadedNum is equal to or exceeds 5.

This modification allows the code to meet your specified requirements, but it is important to clearly define your objectives and identify the actual problem being addressed, as there may be better solutions available.

let loadedNum = 0;
let resolver;
let p = new Promise(r=>resolver=r);
function loaded(){
   loadedNum++
   console.log(loadedNum);

  if(loadedNum >= 5){
     console.log('Entered if statement and should resolve the promise')
     resolver(); 
  } 
  return p;
}

async function int(){
  await loaded();
  loadedNum = 0;
  p = new Promise(r=>resolver=r);
  console.log('Promise Resolved Successfully!')
}

setTimeout(() => loaded(), 2000);
setTimeout(() => loaded(), 4000);
setTimeout(() => loaded(), 5000);
setTimeout(() => loaded(), 6000);
setTimeout(() => loaded(), 7000);
setTimeout(() => int(), 3000);
setTimeout(() => loaded(), 8000);
setTimeout(() => loaded(), 9000);
setTimeout(() => loaded(), 9000);
setTimeout(() => loaded(), 9000);
setTimeout(() => loaded(), 9000);
setTimeout(() => int(), 10000);

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

How can I adjust the vertical position of Material-UI Popper element using the popper.js library?

https://i.stack.imgur.com/ZUYa4.png Utilizing a material-ui (v 4.9.5) Popper for a pop-out menu similar to the one shown above has been my recent project. The anchorElement is set as the chosen ListItem on the left side. My goal is to have the Popper alig ...

Website automation can be simplified by utilizing the Webdriver.io pageObject pattern, which allows for element selectors

Currently, I am following a specific example to define elements within pageObjects using the ID selector... var Page = require('./page') var MyPage= Object.create(Page, { /** * defining elements */ firstName: { get: function ( ...

Is there a way to stop vue-panZoom from functioning temporarily?

I am working with a Grid that includes the use of vue-panZoom. Within the Grid, there is a section that utilizes vue-draggable-resizable, similar to what is depicted in the image below: Image When I drag the gray square (vue-draggable-resizable), the bl ...

What causes Gun.js to generate duplicate messages within a ReactJs environment?

I need assistance with my React application where gun.js is implemented. The issue I am facing is that messages are being duplicated on every render and update. Can someone please review my code and help me figure out what's wrong? Here is the code s ...

Experience the enhanced features and optimized performance of Onsen 2.0 compared to the earlier version

Apologies if this question is too simplistic, but I am finding some conflicting information in the documentation about using Onsen with Monaca. I am currently utilizing Monaca cloud and I prefer to work solely with pure JS, without incorporating Angular ...

Joining Two Texts in HTML with a Link Embedded within

Within my HTML code, I have two specific strings: "Forgotten your password?" and "Please" 'HPERLINK' "to change your password". To manage these strings efficiently in different languages, I utilize a messageBundle file to store constants. This f ...

Error found in Paper.js at line 81: Uncaught TypeError - Unable to access properties of undefined (specifically '1') while utilizing Material UI and Joy UI

I am encountering an issue while using react js with material UI and JoyUI, where I am getting a blank screen. Below is the code snippet causing the problem: import React from 'react'; import { CssVarsProvider } from '@mui/joy/styles'; ...

Ways to replace CSS classes created using makeStyles

To clarify, my development environment is using MUI version 4.12.3. Inside file A, I have a simplified code snippet for a functional component, along with the usage of makeStyles to style a JSX element within the return statement (not displayed here). Ever ...

Modify the CSS using JavaScript after a brief delay

I'm creating a homepage that includes animations. Inside a div, I initially have display: none, but I want it to change to display: block after a few seconds. I've been trying to use JavaScript for this purpose, but I'm struggling to find th ...

Is it feasible to incorporate a third-party JavaScript file into a React application?

I have a JavaScript file from a previous MVC project that generates a basic table using ExtJS. Currently, I'm working on developing a new React application with a navigation bar and sidebar. My goal is to explore the possibility of importing the exis ...

Check the browser's developer tools to access JavaScript files

I recently came across a server at example.noodles.com that is hosting a node.js application. I'm curious if there's a way to access the source files of this application using inspect element or some other method? Up to now, all I've been a ...

Attempting to bind an input parameter using NgStyle in Angular version 2 and above

Issue: I am in need of a single component (spacer) with a width of 100% and a customizable height that can be specified wherever it is used in the HTML (specifically in home.html for testing): number 1 <spacer height="'200px'"></spa ...

Stop unauthorized entry into JavaScript files

Is there a method to secure JavaScript files from unauthorized access? <script src="JS/MyScript.js" type="text/javascript"> It is crucial that users are unable to access the MyScript.js file. I am seeking advice on how to achieve this. Is it even ...

Combining Lodash and Mongoose for efficient data merging

Here is a snippet of code that demonstrates an update method using express.js and mongoose. The goal is to combine the existing MongoDB entity with the JSON object provided in the request payload. exports.update = function(req, res) { if(req.body._id) ...

Developing numerous global objects within the context of JavaScript in Rails

I have an instance object called @cameras in my cameras controller's map method and am extracting necessary values from it for my specific purpose: + @cameras = load_user_cameras(true, false) + @map_data = [] + @cameras.each do |camera| + ...

"Receiving a 404 error when sending a POST request, but getting

When attempting to send a POST request, I encountered a 404 error response from the server. Strangely, when sending a GET request, I received a 200 response. I have experimented with different methods: $.ajax({ type:"POST", url: "script.php", ...

Looking to obtain the coordinates of a draggable element?

After dragging a div around the page and submitting a form, I would like to capture its location on the page so it can render in that same spot when the page reloads. My current question is how can I capture the coordinates or location of the div after it ...

Is it possible for jQuery datepicker to choose a date over a decade in the past?

Recently, I encountered an issue with jQuery-UI's datepicker where it was restricting me to select birthdays only within the last 10 years. This basically meant that users older than 10 years couldn't be accommodated :) I attempted to override t ...

View the selected radio buttons and checkboxes next to each other in real-time before finalizing and submitting

Within my form, individuals have the option to select from radio buttons and checkboxes. The challenge is that I need to display the chosen data on the page before they enter their email and submit! Since I cannot refresh the page, PHP won't work for ...

What is preventing me from utilizing a dynamic import while working with Nuxt3?

I'm currently working on developing a component that allows me to dynamically import icons based on the provided icon name using unplugin-icons. However, I'm facing an issue where dynamic imports don't seem to work when the import path is dy ...