What is the most effective approach for handling user input delays with Async promises?

New to Vue.js and currently exploring the following challenge:

I have a component named PopUp which can be displayed or hidden using functions of the same name.

My goal is for the popUp.show() function to return a promise that contains information about how the user closed the popUp (such as button press, clicking outside the popup, etc).

The main issue I'm encountering is figuring out how to efficiently wait for the closure information. Initially, I considered using a loop, but this approach seems inefficient and could potentially stall the entire program.

One idea I had was to implement something like this:

async show() {
  //Insert Show PopUp code
  return this.resolve()
}

hide() {
  //Insert hide code
  this.closed = true;
}

resolve() {
  while(!this.closed){}
  //insert build response object code
  return response
}

I'm wondering if there's a better way to listen for changes in a variable rather than employing a looping mechanism.

Appreciate any insights!

Answer №1

In response to the feedback provided, it is advised that the function show() should be designed to return a Promise and then monitor 'click' events. Upon detecting a click on the specific element (such as the close button or outside the dialog), the resolve function should be executed.

The suggested pattern resembles the following:

function show() {

  // create and return a new Promise immediately
  return new Promise((resolve) => {

    // event listener for clicks
    const responder = (evt)  => {
      let target = evt.target;

      // remove the event listener and resolve when any of the dialog-closing elements are clicked
      if (target === one_of_the_dialog_closing_elements) {
        document.removeEventListener('click', responder);
        resolve(target);
      }
    };

    // set up the click event listener
    document.addEventListener("click", responder);
  });
}

Answer №2

A loop can be detrimental as it consumes CPU resources unnecessarily. Monitoring the status of closed using $watch is a possibility, but its reactivity remains uncertain and may not be required.

The appropriate methods to modify closed are through invoking hide and show functions. Here is a potential solution:


show() {
  if (this._resolvePopup)
    this._resolvePopup(); // handle multiple show() calls

  return new Promise(resolve => this._resolvePopup = resolve);
}

hide() {
  this.closed = true; // view-only access
  if (this._resolvePopup) {
    this._resolvePopup();
    this._resolvePopup = null;
  }
}

Answer №3

Upon analyzing the input provided in this query, I tackled the solution by utilizing the given framework as a reference:


display() {
  //Implement Show PopUp function
  return new Promise((resolve) => {
      const responseHandler = (body: Response) => {
        resolve(body);
      };
      resolve = responseHandler;
    });
}

conceal() {
  //Add conceal code here
  resolve();
}

private resolve() : void

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

Navigating the world of TypeScript and SystemJS without the confines of Angular

Lately, I've been delving into TypeScript through research and simple "hello world" projects. However, I've hit a roadblock when it comes to using System.js with TypeScript that I just can't seem to overcome. Most tutorials and demos online ...

Developed a new dynamic component in VUE that is functional, but encountered a warning stating "template or render function not defined."

I'm currently working on a dynamic markdown component setup that looks like this <div v-highlight :is="markdownComponent"></div> Here's the computed section: computed: { markdownComponent() { return { temp ...

Having trouble aligning a div in the middle of a slick-slider item using flex styling

I've created a slick slider component in Vue, and I'm facing an issue with centering a circular div inside each of the slider items. Despite trying to align and justify center along with adding margin:auto for horizontal centering, I can't s ...

Error in parsing string data in Django Chart.js ajax using javascript

I'm currently working on creating a chart web page using Django and Chart.js within the views.py file of the Django framework. class ChartView(TemplateView): template_name = 'graph.html' def get_context_data(self, **kwargs): ...

Create a typescript class object

My journey with Typescript is just beginning as I delve into using it alongside Ionic. Coming from a background in Java, I'm finding the syntax and approach quite different and challenging. One area that's giving me trouble is creating new object ...

Displaying a Dynamic Loading Animation While Making an AJAX Call with jQuery

When a user clicks on the active status button, it should switch to inactive with a red color, and vice versa. Currently, I can update my status in the backend, but I have to refresh the page to see the changes every time! My requirement is that during t ...

A guide to implementing localStorage in TypeScript

When attempting to assign the object item to Product using this code: localStorage.setItem("Product", JSON.stringify(item)) The JSON string of item is not properly assigned to Product. Is there a solution to this issue? ...

Using JavaScript to sort through JSON data arrays

I am dealing with a JSON data structure as shown below: var data = [ { "type": "Feature", "id": 1, "properties": { "name": "William", "categorie": 107, "laporan":"Fire", "time":1, ...

What is the best way to integrate a jQuery Plugin into an Angular 5 application powered by TypeScript 2.8.1

I am trying to incorporate jQuery into my Angular 5 project using TypeScript 2.8.1. I attempted to follow Ervin Llojku's solution but it didn't work: First, install jquery via npm npm install --save jquery Next, install the jquery types npm i ...

HTML code for a grid view that allows users to expand and collapse rows in a

I'm looking for a gridview with 'n' rows, each containing 4 columns/items to be displayed. My goal is to accomplish this using an Html/Javascript/Vuejs template exclusively. The desired view should look like this: https://i.sstatic.net/kSx7 ...

What is the process for generating a tree structure from an HTML element?

This particular element is found within my Vue2 application: <div class="child-elements-container draggable-container"> <div> <div entity-type="entitytype1" type="elementType" id="2" class= ...

Error message appears: "Unable to access 'upgrade' property of undefined" upon launching Vue application

Everything was running smoothly with my project for a few months. I could easily execute npm run serve without any issues, even when switching networks. But now, no matter what I do, I can't seem to get the server to start again. The error message I&a ...

Issue: The system is unable to locate the "moduleIntro.js" module while executing the "http" command

I recently embarked on a journey to learn Node.js and decided to experiment with the 'http' module. Here is a snippet of the code I tried to run: var http = require('http'); http.createServer(function (req, res) { res.write('H ...

The effectiveness of the javascript widget is hindered by the absence of the meta viewport tag,

As I work on creating a widget to appear at the bottom of webpages, I've encountered a styling issue. The widget's display varies based on whether the webpage includes a specified meta viewport tag or not. <meta name="viewport" content="width ...

Using Mongoose's $pushAll will replace existing elements in the array

I'm currently facing an issue where updating comments on a document results in the array being overwritten by the new information. Any insights on why this might be happening? Confession.findOne({_id: confessionID}, function (err, confession) { i ...

Working with JSON objects in JavaScript using CodeIgniter framework

I am encountering an issue with my Jquery function in the controller. It seems to be unable to read the Json_encoded object, even though I am using codeigniter. Any ideas why? $(this).ajaxSubmit({ type : "POST", u ...

What are alternative ways to communicate with the backend in Backbone without relying on model.save()?

Is there a more effective method to communicate with my backend (node.js/express.js) from backbone without relying on the .save() method associated with the model? Essentially, I am looking to validate a user's input on the server side and only procee ...

Revamp the usage of $fetch in nuxt3 by implementing a global onRequest handler

Would it be feasible to utilize a global onRequest handler in Nuxt3 to $fetch data and append specific details to each request? It was a straightforward process with nuxt2 and axios /plugins/axios.js export default function ({ $axios, store, req }) { $a ...

Even after deleting the circle from the Google Map, the label still persists within the Google Map Javascript API

Even after removing circles on the Google Map, the labels still persist. I use InfoBox to display labels on circles like this: myOptions.content = datadetail[i].Count; var ibLabel = new InfoBox(myOptions); ibLabel.open(map); I am trying to clear the circ ...

Sharing JSON data between two Backbone views

Could you provide some guidance on how to pass dynamic JSON data from one view to another? In the initial view, I am creating the JSON object using the following syntax: json.push({ first: value, second: value }); ...