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

Is the term 'Literal' in Javascript Arrays simply referring to its dynamic nature, allowing it to be modified at any time?

I'm confused why Mozilla refers to this as an Array 'Literal' when it's declared using the VARIABLE keyword and its content can be modified... var drinks = ["Espresso", "Latte", "Cappuccino"]; Could someone shed some light on this for ...

The ng-click event in AngularJS does not function as expected when nested within another ng-repeat loop

I am facing an issue with ng-click in my Angular application (version 1.0.4). The first ng-click works fine, but the second one does not. <div class="menu-group" ng-repeat="module in modules"> <div ng-click="toggle($event, $parent)" ...

Using NextJS to pass a parameter to an onClick function

I've been using the react-simple-star-rating package in this sample code. However, I'm facing an issue: Within my trains parameter, there is a variable id that I would like to pass to the handleRating function using onClick, but I can't see ...

Substitute the ajax reply with the text currently displayed

I am facing an issue with the AJAX response in my HTML page. Currently, the response is being appended on top of the existing text instead of replacing it. Here is a snippet of my code: <html> <head> <h2>This is a test</h2> ...

The Vue2 @click event does not function properly when using v-html within a different component

I currently have a sign up form that includes an Alert component for displaying any errors. One of the conditions may prompt a message saying "You already have an account, click here to log in". The error messages are passed as props to the "Alert" compon ...

Obtain the height and width of the original images from the href and assign them to your attributes using jQuery

Hey there pals, I'm currently on a mission to fetch the dimensions (height and width) of an image from a hyperlink and then insert those values into its attribute. This task has got me going bonkers! Here's my snippet: <figure> <a ...

Is there a way to input data into an AngularJS modal?

I'm looking for some assistance : How do I go about loading data into the content of an angular modal? Is there a way to load custom data for a selected item? ............................................................. This is the code ...

Successfully updating a document with Mongoose findByIdAndUpdate results in an error being returned

findByIdAndUpdate() function in my code successfully updates a document, but unexpectedly returns an error that I am having trouble understanding. Below is the schema that I am working with: const userSchema = mongoose.Schema({ phone: String, pas ...

Using Laravel to retrieve the selected value of a dynamically generated radio button through a for loop in jQuery

In my view, there is a form with dynamically populated radio buttons sourced from the database. The code snippet for this functionality is as follows: <div class="row"> @foreach($status as $s) <div class="col-md-6"> <label class ...

Issue with Mobile Touch Screen Preventing Vertical Scrolling

Currently experiencing difficulties with a div element that is not allowing touch and vertical scroll on mobile devices. Although scrolling works fine with the mouse wheel or arrow keys, it does not respond to touch. Have tested this on various devices and ...

Add CSS styles directly into the shadow-root instead of the head tag | Vue.js and Webpack

Currently, I'm developing a widget that can be embedded on websites using Vue.js along with vue-custom-element. Everything was going well until I encountered an issue. The problem arises when trying to integrate a component (along with its CSS) from ...

What methods can be employed to maintain a consistent width for a multi-line span that aligns with the content?

Inside a div, I have 2 spans. When the content of the first span is short enough to fit on one line, the span's width matches the text content and positions the second span next to it. If the content of the first span is long and causes it to wrap, t ...

When placed above in the template, the ng-model is causing the ng-repeat to not display anything

Currently, I am teaching myself Angular by following a tutorial at https://docs.angularjs.org/tutorial, but with my twist of using different data to keep things interesting. My struggle seems to stem from a simple mistake I might be making, compounded by ...

Trouble with Jsonp when using the getJSON function in jQuery

$(document).ready(function() { $.getJSON("http://quanta.net16.net/wordpressnew/test.php?jsoncallback=?", function(data) { alert('swag'); }); }); This is the JSON request I'm making and my data is properly contained within ?({object} ...

Determine if a certain value is present in a JSON data structure

Exploring the depths of NodeJS, I am utilizing a JSON Object for user validation. JSON content (users.json): { "users": [{ "fname": "Robert", "lname": "Downey Jr.", "password": "ironman" }, { "fname": "Chris", ...

Input the variant number TypeScript as the key value pair

I'm struggling to input an abi key "5777" in Typescript. When I receive a network ID and try to set it in the networks key, the linter displays an error. My issue is that I need to specify "networkId" and it's not always a fixed value like "5777 ...

Am I utilizing the htmlspecialchars function properly?

My main objective is to protect the user from malicious code and prevent XSS attacks. I have implemented a series of checks to filter the user's input before storing it in the database. The user input is stored in the $post variable. $post = htmlspec ...

Jest throws an error: require function is not defined

I've been struggling with an issue in Angular for the past 3 days. I'm using [email protected] and [email protected]. I even tried downgrading and testing with LTS versions of node and npm, but I keep encountering the same error. Here ...

Looking for a way to retrieve JSON data from an HTML page using JavaScript? Look no further

There is a page that sends me JSON data. You can make the request using the GET method: or using the POST method: argument --> unique_id=56d7fa82eddce6.56824464 I am attempting to retrieve this information within my mobile application created with Inte ...

ng-if is executed prior to the specified time

This unique Soundcloud player was created using Plangular, a directive that utilizes AngularJS and the Soundcloud API. Due to certain restrictions with third party apps not being able to stream some Soundcloud tracks, I have implemented ng-if="track" and n ...