Create an asynchronous method within an object-oriented programming (OOP) class

Presenting my Activity class.

export class Activity {
  _name: string
  _goIn: boolean
  
  constructor(name: string) {
    this._name = name;
    this._goIn = false;
  }

  isGoIn() {
    return this._goIn;
  }
  
  setGoIn() {
    // instructions to asynchronously change the value of _goIn to true
    this._goIn = true;
  }
  
  setName(name: string) {
    return this._name = name;
  }
}

The task at hand involves updating the _goIn value to true in an asynchronous manner.

Regards

Answer №1

If you want to defer code execution until after the call stack has been emptied, consider using this approach:

return Promise.resolve().then(() => this._goIn = true);

class Task {
  _name
  _goIn
  
  constructor(name) {
    this._name = name;
    this._goIn = false;
  }

  isGoIn() {
    return this._goIn;
  }
  
  setGoIn() {
    return Promise.resolve().then(() => this._goIn = true);
  }
  
  setName(name) {
    return this._name = name;
  }
}

// example
let task = new Task("test");
task.setGoIn().then(() => console.log("2. Asynchronous... it is now", task.isGoIn()));
console.log("1. Synchronous... it still remains", task.isGoIn());

You can also achieve the same with async syntax:

async setGoIn() {
    await null;
    this._goIn = true;
}

class Task {
  _name
  _goIn
  
  constructor(name) {
    this._name = name;
    this._goIn = false;
  }

  isGoIn() {
    return this._goIn;
  }
  
  async setGoIn() {
    await null;
    this._goIn = true;
  }
  
  setName(name) {
    return this._name = name;
  }
}

// example
let task = new Task("test");
(async function() {
    await task.setGoIn();
    console.log("2. Asynchronous... it is now", task.isGoIn());
})(); // execute immediately
console.log("1. Synchronous... it still remains", task.isGoIn());

If you have access to queueMicroTask or setTimeout, then these are non-promise alternatives:

return setTimeout(() => this._goIn = true);

setTimout returns the id of the timeout without indicating when the callback will be executed. queueMicroTask returns undefined. Therefore, a Promise solution is generally preferred as it allows for easier chaining and usage within asynchronous contexts.

Answer №2

async checkIfGoing() {
    return this._going;
 }

Don't forget to utilize await within a separate async function in order to access the value. This tip should be beneficial for you. Alternatively, consider returning a promise instead of utilizing the _going method.

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

experimenting with adding fresh choices to dropdown menu using ajax and jquery

When attempting to load a list of locations through ajax/jQuery, I encounter an issue. After typing a letter into the input field, the first response is displayed but subsequent responses are simply appended to it. I have tried using .html('') an ...

Unexpected behavior involving the onchange event, input validation, and the enter key

One challenge I encountered was implementing validation for a date input field in a form. The requirement was to only allow dates starting from today up to a maximum of 3 years in the future. If a valid date is entered, a modal should appear; otherwise, an ...

"Experience the power of using Selenium with Node.js in an asynchronous function

I'm currently developing a simple program that retrieves the titles of all the links when conducting a search on Google using Selenium Take a look at the code below: const {Builder,By, Key, until} = require('selenium-webdriver'); driver = ...

Adding event listeners to elements created dynamically

I am facing an issue with some dynamically generated divs from a JavaScript plugin. The divs have a class .someclass which wraps existing divs. My goal is to add a class to the children of .someclass. I attempted to achieve this by using the following code ...

Transferring PHP array to JavaScript with the help of AJAX

I've been working on integrating Google Maps and Instagram in a project of mine. My main challenge is figuring out how to pass the coordinates of Instagram photos from my PHP file to my JavaScript file using AJAX. I'm quite lost when it comes to ...

Assign an onClick event to a Button that was dynamically generated within a loop in JavaScript

Is there a way to set the onClick property for buttons created within a loop? I've tried using JQuery with no success. for(started somewhere... var button = document.createElement('button') var div = document.createEl ...

Interactive Thumbnail Selection for HTML5 Video

Having trouble with creating thumbnails? I managed to solve the cross-domain issue using an html2canvas PHP proxy. No error messages in the Console, but the thumbnails are unfortunately not showing up - they appear transparent or white. Here is a snippet ...

What is the best way to generate an extensive table with HTML and AngularJS?

I am looking to implement an expandable table feature where a single header with a plus icon can be clicked to reveal the child rows beneath it. Currently, I have been able to achieve this functionality. However, I am facing an issue where the child rows ...

Is there a way to select a checkbox in Google Forms using the console?

I need help with a script I'm creating to automatically populate Google Forms. I am able to select checkboxes using querySelector, but they don't have a .click() method or similar. How can I go about checking the checkboxes? ...

How can Express JS be configured to make URL calls from a local environment?

I encountered an issue with my code (Weather App using OpenWeatherMap Api) when I attempted to move my apiKey and apiUrl to the .env file. An error appeared in the terminal, but it's unclear why it occurred. Below is my code: const express = require( ...

What is the best way to transfer the "user" object from TopBar.js to App.js in my project?

In my project, TopBar.js functions as an AppBar component responsible for handling user authentication. When a user logs in, I receive an object called "user". My goal is to export this "user" object to App.js. If I am successful in exporting it to App.js ...

angular table cell with a show more/less button

I'm trying to create a button that can hide/unhide text in a table cell if the length is greater than a certain number. However, the current implementation is not working as expected. The button ends up opening all texts in every cell, and it only wor ...

Ways to expand a Bootstrap input field by clicking on it:

I have successfully created a search bar in my navbar, but I am looking to add functionality that allows the input field to expand to its normal size when clicked. I believe this will require some JavaScript implementation, however, I am unsure how to proc ...

Is there a way to confine a jquery script within the dimensions of the container div?

I have recently created a gallery with navigation buttons in jQuery. As a newcomer to jQuery, I wrote a small script that adjusts the margin of a div container by a fixed amount. The script is functioning properly, but it extends beyond the top and bottom ...

The click event listener declared with v-on inside a Vue Component fails to trigger

I am currently working on a Vue instance for a sidebar within my application that displays a list of menu items. In order to achieve this, I have created a local component with the following template structure: template:'<div><li class="cust ...

Transforming Jquery into vanilla JavaScript and sending a POST request

Hey everyone, I'm in the process of converting Jquery code to pure javascript and encountering some difficulties with the following snippet: $.post('ajax_data',{action:'service_price',service:service,quantity:quantity,dripfeed:drip ...

What is the best way to redirect nodejs requests to a separate nodejs application?

Hello! I am currently working on a project to create an API gateway using Node.js and Express. The goal is to showcase a small-scale microservices architecture by routing requests to different microservices. For instance, if I have microservices A, B, and ...

Cannot locate element using React Testing Library with the selector: [data-testid="task"]

I've encountered an issue while testing a Task component that should be rendered after submitting a form. I'm utilizing redux-toolkit, but despite setting data-testid="task" for the Task component, it doesn't appear in the test DOM ...

jQuery template does not respond to input text when a click event is enabled on an iPhone device

Below is a jQuery template I have: <div class="parent-class"> <div class="sub-class"> <div clas="sub-input-class"> <input type="text" /> </div> </div> </div> Recently, I ...

What is the reason behind this Uncaught TypeError that is happening?

After converting my questionnaire to a PHP file and adding a validation script, I encountered an error: Uncaught TypeError: Cannot set property 'onClick' of null The error is pointing me to line 163 in my JavaScript file, where the function f ...