Linking several asynchronous functions together in JavaScript

class Calculation {
  constructor(num) {
    this.num = num;
  }

  performAddition() {
    // code
  }

  performSubtraction() {
    // code
  }

  performMultiplication() {
    // code
  }

  performDivision() {
    // code
  }
}

const getResult = async () => {
  const result = await new Calculation(10)
    .performAddition(30)
    .performSubtraction(5)
    .performMultiplication(2);

    console.log(result); //prints the final result
};

getResult();

Is there a way to achieve chaining of methods in JavaScript where each method can be awaited for asynchronous execution, similar to mongoose queries?

Although regular calculations are synchronous, if we were to consider them as asynchronous operations, what would be the correct implementation to achieve the desired functionality?

Answer №1

To create a calculator object with methods like add, subtract, etc., you can assign an internal property that holds a Promise and update it when the methods are called. Finally, retrieve the Promise value from the instance:

class Calculator {
  constructor(num) {
    this.promise = Promise.resolve(num);
  }

  add(arg) {
    this.promise = this.promise.then(res => res + arg);
    return this;
  }

  subtract(arg) {
    this.promise = this.promise.then(res => res - arg);
    return this;
  }

  multiply(arg) {
    this.promise = this.promise.then(res => res * arg);
    return this;
  }
}

const getResult = async () => {
  const result = await new Calculator(10)
    .add(30)
    .subtract(5)
    .multiply(2)
    .promise;

    console.log(result) //prints the final result
};

getResult();

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

Unable to successfully download npm packages - encountered an error running `[email protected] install: `node-pre-gyp install --fallback-to-build` on Ubuntu 18.04 system

I am facing an issue while trying to npm install (using lerna bootstrap) a project on Ubuntu 18.04. The error I encounter is related to node-pre-gyp install --fallback-to-build. I have attempted installing node-gyp, node-pre-gyp, and apt-get build-essenti ...

Ways to have a React Component trigger a function with each state update

Using this specific component, the getDisplay function is triggered on every update like normal. When the <div> element is clicked, it becomes hidden: class Example extends React.Component { constructor(props) { super(props); thi ...

Utilize Recurly's Node to generate a transaction with stored billing details

I need help creating a transaction using Recurly stored billing information. I am currently using the node-recurly module in my Node.js application. https://github.com/robrighter/node-recurly Below is the code snippet that I have written: recurly.transa ...

Code for object creation, inheritance, and initialization

In the code snippet below, a class is defined for managing input events such as mouse, touch, and pointer: // base.js export default () => { return { el: undefined, event: undefined, handler(ev) { console.log('default handler&a ...

"Exploring the various configurations for session handling in NodeJs

I am trying to implement a login system using the express-session module. I'm unsure if I have set everything up correctly, especially when it comes to the secret option. Currently, my initialization code for express-session looks like this: app.use( ...

The presence of a .js file is causing a blockage in the loading

As a beginner in the world of jquery/web design, I decided to download a template to experiment and get more familiar with it. Unfortunately, I encountered an issue with a specific script that is causing my jQuery to not load properly. Here is the snippet ...

I will see the "undefined" entity displayed in the bar chart created using react-chartjs

Using the react-chartjs-2 library, I created a bar chart with the following data: const chartData = { labels: ['Dealer1', 'Dealer2', 'Dealer3', 'Dealer4', 'Dealer5', 'Deal ...

Leveraging react-router for automatic redirection after form submission

My goal is to implement a search functionality on the page where users can enter a search term (name, email, username) and have the page filter out one card from all the cards based on the search value. I believe that upon pressing enter, we should redirec ...

Determine whether the specified date falls on a public holiday within the selected

I'm currently working with Angular 12 and I need to determine whether today is a regular workday or a day off for employees, including weekends and public holidays. I attempted to use the date-holidays package by importing it like this: import Holida ...

Displaying or concealing HTML elements using AngularJS while a modal is open

Looking for a way to display a loading spinner icon on my page when a user triggers a button that opens a modal, and then have the spinner disappear once the modal is open and its content has loaded. Currently, I've managed to make the spinner show up ...

Guide on linking an XML reply to TypeScript interfaces

Currently, I am faced with the task of mapping an XML response (utilizing text XMLHttpRequestResponseType) from a backend server to a TypeScript interface. My approach has been to utilize xml2js to convert the XML into JSON and then map that JSON to the Ty ...

Exploring the Power of JQuery and Iterating with For-

I'm currently facing a small issue with my code. I need to retrieve information about each module when I display the hidden table row. The information is fetched from the page {modules/$moduleid}. While I understand how to utilize AJAX, my challenge l ...

show information from json onto an html page with the help of jquery

I'm looking to showcase buttons from a JSON file within a simple block. Here's the JSON data for movies: { "movies": [ { "title": "Mena", "movieid": "1", ...

Issue with React Hot Toast not displaying properly due to being positioned behind the <dialog>

The Challenge of Toast Notifications Visibility with <dialog> Element tl;dr When utilizing the native dialog.showModal() function, the <dialog> element appears to consistently remain on top, which causes toast notifications to be obscured by ...

Troubleshooting Nested jQuery Plugin Selector Problems

I'm looking to have the ability to nest one plugin inside another. However, my selectors seem too broad and are capturing elements within the nested plugin as well. For instance, consider the following HTML structure: <div class="my-plugin"> ...

Guide to including configuration settings in locals for Sails.js

Currently working on a webapp with Sails.js, I am looking for ways to set up different configurations for development and production modes. Initially, I attempted to store the configuration key in config/local.js, but unfortunately, it did not yield the de ...

Are moment.js and moment.php interchangeable?

Recently, I developed a JavaScript script utilizing moment.js and I am looking to mirror it using a cron job in PHP. In my search for moment.js equivalents in PHP, I came across this https://github.com/fightbulc/moment.php ...

Mongoose fails to save due to an error stating "undefined id"

Having some trouble with the Mongoose save function... In my user model file: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const User = mongoose.model('User', { name: Schema.Types.Mixed, gender: String, ...

React: encountering issues with accessing component props after page refresh

Whenever I try to reload the 'details' page (not the homepage) on my app, I encounter the following error: "TypeError: Cannot destructure property 'flag' of 'country' as it is undefined." It seems that the data is ...

Step-by-step guide on programmatically activating a radio button

I am working with a radio button and input field. I need the ability to programmatically toggle the radio button so that when this.iAreaOfCoverageForThresholdPasser.average-height is set to true, the radio button appears highlighted. Snippet of HTML: < ...