Strategies for increasing a value within an asynchronous function

I'm facing an issue with incrementing the variable loopVal inside a promise. I've tried to increment it without success. Any ideas on how to make this work?

const hi = function(delay) {
  let loopVal = 1;
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Resolved Successfully", loopVal);
      resolve();
      loopVal++;
    }, delay)
  })
}

const bye = async() => {
  await hi(1000);
  await hi(1000);
  return "bye";
}

bye().then((value) => console.log(value));

Answer №1

Initially, the variable loopVal exists only within the function and any modifications to it are lost once the function ends.

Additionally, you fail to return the updated value from the promise.

To address this issue, you may consider placing this variable in a scope where it can serve as both an argument and a return value for your hi function.

const hi = function(val, delay) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Successfully Resolved", val);
      resolve(val+1);
    }, delay)
  })
}

const bye = async() => {
  let val = 1;
  val = await hi(val, 1000);
  val = await hi(val, 1000);
  console.log("Final result", val);
  return "goodbye";
}

bye().then((value) => console.log(value));

Answer №2

Your code currently resets the loopVal to one each time the function is called, causing a lack of state persistence between function calls. To solve this issue, you can use a closure that returns a function which allows you to maintain the variable's state without relying on a global variable.

const hello = (function() {

  let loopVal = 1;
  
  return function(delay) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log("Resolved Successfully", loopVal);
        resolve();
        loopVal++;
      }, delay)
    })
  }
}());

const goodbye = async() => {
  await hello(1000);
  await hello(1000);
  return "goodbye";
}

goodbye().then((value) => console.log(value));

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

Do I need to include success as a parameter in my Ajax call even if my function does not return any values?

When an image is clicked, I trigger an ajax call. The image includes an href tag that opens a different page in a new tab upon click. The purpose of this ajax call is to record the user's clicks on the image for telemetry purposes in a database table. ...

The MomentJS difference calculation is incorporating an additional hour

I am currently working on a project that involves time calculations. const currentCETTime = moment.tz('2020-03-18 15:58:38', 'Europe/Madrid'); const limitCETTime = moment.tz('2020-03-18 18:00:00', 'Europe/Madrid') ...

Tips for excluding specific elements when clicking on a document

JavaScript $(document).click( function () { alert("Hello there"); } Web Development <div id="wrapper"> <div id="inner-1"> <div id="sub-inner1">Sub Inner1 Content</div> <div id="sub-inner2">Sub Inner2 Content&l ...

Tips for Creating an Upward-Dropping Dropdown Menu in HTML/JavaScript When Space is Limited on the Page

Hello, I am currently seeking a solution to adjust my dropdown menu so that it appears above instead of below when the page doesn't have enough space to display it fully. My tools for this project include HTML, Javascript, CSS, and JQuery exclusively. ...

Steps for navigating to a different page by clicking on a gridview row

Currently, I am utilizing a grid view on my webpage. My specific request is that upon clicking on any row within the grid, it should redirect to a separate page where all the details of the selected row will be displayed. Appreciate your assistance! ...

The Jasmine test in my Angular project is experiencing a timeout issue, displaying the error message "Async callback was not invoked within 5000ms", despite the fact that no async function is being used in the

Reviewing the source code: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { IonicModule } from '@ionic/angular'; import { HomePage } from './home.page'; import { LevelGridComponent } from &a ...

Display loader while waiting for file to be loaded

I am utilizing ajax to retrieve a file. The loading animation is functioning properly with the ajax request, however, the file size is notably large. I am interested in implementing a preloader that will display until the file has finished loading. ...

Building on the Vuejs3 and Vuex4 framework, create a conditional rendering feature that triggers upon

I have a unique setup where custom objects are used to hold child objects full of data. The child objects start with null values for all properties, allowing them to be filled with data from remote sources when referenced. This results in a lazy-loading sy ...

Develop a Vue.js component embedded within another component to manipulate data stored in the parent

After reviewing a few answers that partially address my question, I realized there is more to explain. In our Laravel project website layout, we utilize a global #app div. This means all pages share the same main Vue instance, prompting me to segregate ke ...

When I implement JavaScript on my website, my HTML content does not show up

Whenever I try to fetch content from a specific URL using AJAX and a script, my HTML content does not show up. In other words, the table element is not displayed on the page. Instead, I am able to retrieve data from the specified URL and display it in an a ...

Is there a way to categorize data and sort it by using an action and reducer in redux?

I have developed a filtering system that allows users to filter data by different categories such as restaurants, bars, cafes, etc. Users can select whether a specific category should be displayed or not, and this information is then sent to the action and ...

Experiencing difficulty moving information from React form to DATA.txt file through Express

I've tried various things, but I keep encountering the same error. Changing the file path didn't seem to make a difference. The current structure of my project is as follows: {nodemodules,public,scr (containing all files including App.jsx),DATA. ...

Is there a way for me to determine when the modal animation has completed?

I'm currently using the modal feature in twitter-bootstrap and I am curious about how long it takes for the modal to appear before triggering an alert. To better illustrate my point, you can check out this example: HTML <button id="mod" class="b ...

Experiencing SyntaxError when utilizing rewire and mocha for Node.js testing. Unexpected token encountered

Trying to test a function exported from a nodejs file, I am utilizing q to manage promises. The function returns a promise that is either resolved or rejected internally through a callback. Within this callback, another function from a different location i ...

When attempting to view the PDF file, it appears completely void

After spending countless hours on this task, I'm still not making any progress. My goal is to download a PDF file from my server while currently running the operation on localhost. However, whenever I open the downloaded PDF, all I see is a blank whit ...

Displaying HTML content from a Vuejs response within a Dialog box

After receiving a response from the server via a REST request in HTML format, I have saved it in a data:[] variable. When I log this data on the console, it appears as raw HTML code. This reply is currently stored as a String, and my challenge now is to co ...

How can I efficiently remove elements from the end of an array in Vue.js?

Is there a way to splice data starting from the back with a higher index? When clicking on the .delete div, how can I make it so the .image-box div deletes starting from the end? I need help implementing this feature in my code. Here is a snippet: < ...

Guide on accessing a local image while setting the background image using JavaScript

I am trying to set a background image from a local source on my computer. Below are two lines of code, one that works and one that does not: (the local one fails) _html.style.backgroundImage = 'url("urlsourceblahblahblah")'; _html.style.backgro ...

Display the number in a formatted manner without displaying any zeros in the decimal part

Can you help me with a decimal number display issue I am having? <nested:text property="product.price" maxlength="5" onclick="javascript:validatePriceValue(this);"/> number displayed as 44 44.00 I want to use J ...

jQuery providing incorrect measurements for an element's height

I am encountering an issue with obtaining the height of the #header element in my AngularJS application. Despite using jQuery, the returned height seems to be incorrect. The current code snippet looks like this: $(document).ready(function() { function ...