What is the best way to implement an onReady promise in a JavaScript application?

Exploring some Advanced topics in JS I am currently diving into and there is an interesting concept that's piqued my curiosity.

I've been developing a VueJS application and now I'm looking to expose certain data and even methods from Vue outside of the Vue framework itself, leveraging vuex along the way.

The goal here is to allow users to utilize standard JavaScript on the front end to enhance the functionality of the application.

The vision is for users to incorporate something like this in their front-end code. I have come across various JS frameworks/apps that adopt a similar approach.

MyApp.onReady.then(function(instance) {
    // utilize the instance object
    var email = instance.data["email"]
    var name = instance.data["name"]
    var isComplete = member.isComplete
})

Now, what I'm striving to comprehend is the implementation required in my App to bring the above scenario to life.

Based on the code provided, it seems there is a Class MyApp that is instantiated with new MyApp({}), featuring a promise being resolved, yet the actual steps to achieve this remain uncertain to me.

Answer №1

Below is an example demonstrating how to return a promise.

const Application = {
  onLaunch() {
    return new Promise( (resolve, reject) => {
      // Perform your tasks here and then call resolve().
      // Example below
      setTimeout(()=>{resolve()}, 1000)
    })
  }
}

To use it, make sure to call onLaunch(), not just onLaunch.

Application.onLaunch().then(()=>{
  // Add your code here.
})

Answer №2

Here is a method to achieve the desired outcome:

class NewApp {
  constructor(data = {
    email: null,
    name: null
  }) {
    this.data = data;
  }

  get ready() {
    return new Promise((resolve, reject) => {
      resolve(this);
    });
  }
}

const onReadyFunction = instance => {
  const {
    email,
    name
  } = instance.data;

  console.log(`${name}'s contact email is: ${email}.`);
};


const john = {
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="780c1715381e19131d15191114561b1715">[email protected]</a>',
  name: 'John'
};

const application = new NewApp(john);

application.ready.then(onReadyFunction);

Answer №3

By adding the async keyword to a method, it automatically returns a promise.

const AppName = {
  async onReady() {
      // Perform tasks here and then return to resolve.
      // Raising an exception will trigger a rejection.
  }
}

How to use:

AppName.onReady().then(()=>{
  // Application is ready
})

If your code is within an async function, you can simply use await.

Usage:
// Must be inside an async function
await AppName.onReady()
// Application is ready

To use await at the root level, wrap it in an immediately invoked function:

(async()=>{
   await AppName.onReady()
})()

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

"Enhancing JqGrid functionality with inline editing and custom formatters

I'm currently working with a column model that looks like this: { name: 'CostShare', index: 'CostShare', width: 50, formatter: 'number', formatoptions: { decimalPlaces: 2, suffix: "%" }, resizeable: true, align: 'ce ...

Tips for keeping notification icons in the upper right corner of the box?

I am facing an issue with absolute positioning where the notification icons I've positioned to the top-right corner of a box are moving away when the screen size changes. Desired appearance of the image Actual appearance when screen size is adjusted ...

Angular route unable to detect Passport User Session

The navigation bar in the header features buttons for Register, Login, and Become a Seller. Upon user login, it displays logout and view profile buttons. This functionality is operational on all routes except one, causing a client-side error. user not def ...

Sketch a line extending from one element to the next

Is there a way to create a styled line that starts from the center of one <td> element and ends at the center of another? I attempted to use the jQuery Connections plugin but it only connects the edges of the elements, not their centers. The plugin ...

How to disable or enable a submit button in jQuery 1.8

Recently, I upgraded from jquery version 1.5.2 to 1.9 and encountered an issue with my disabled buttons not functioning properly. The buttons should become enabled after the form fields are filled out, allowing the user to either remove or save the infor ...

Encountering issues with loading Angular formControl

I've been going through an Angular tutorial on forms, which you can check out here. In my 'datasources.component.html' file, I have the following code: <form [formGroup]="queryForm"> <label>Query: <input type="text" formCont ...

Set a value for the hidden field on the page using client-side scripting

When working with an ASP.net application, I often use Page.ClientScript.RegisterHiddenField("hf_Name", value). However, I am curious about how to override or set a new value for the same Hidden Field 'hf_Name' in the code behind. Can you provide ...

Using jQuery each, the output is an undefined Object or HTMLElement

Using jQuery's each/getJSON to iterate through a data.json file, collect and format the data, and display it on the page within the #output div. The functionality is working correctly, except for the unexpected addition of [object HTMLElement] that a ...

Create JavaScript variable from either HTML or database sources

Hello, I am trying to implement a counter that retrieves its value from a JavaScript file, but I would like to customize it. Below is the JavaScript code: function updateCounter(count) { var divisor = 100; var speed = Math.ceil(count / divisor); ...

Trouble with Rails partial refresh using Ajax feature

On the homepage, I would like to display article information to the user. When the user clicks on the My Articles link, the relevant information should be shown without refreshing the entire page: Here is the code for the ArticlesController: def index ...

How can you access a sibling of the parent element of the current element in Jquery?

I'm working on an HTML project where I have a select field. Depending on the option selected, I need to update the price field with the corresponding price fetched using Ajax. Additionally, I want to be able to input multiple rows by clicking on the ...

How does assigning a checkbox's value as 'undefined' result in the addition of ng-invalid?

I'm facing an issue with a checkbox in my Angular project. The checkbox has a false value of undefined, and even though it's not marked as required, the form doesn't validate when I check and uncheck it. This is because the class ng-invalid ...

Just diving into JavaScript, what makes jQuery so powerful?

As a newcomer to javascript (although functional programming is no problem for me), I find myself questioning some of the design choices made by jQuery. Is it too late to make changes now, or are they simply too ingrained in the framework? For example, the ...

Exploring Angular: Techniques for searching within nested arrays

I am looking for a function that can search and filter the largest value in a nested array, and then return the parent scope. Here is an example of my array: data = {"people": [{"male": [ {"name": "Bob" ,"age": "32"}, {"name":"Mike", "age ...

When you open the link in a new tab, the form submission does not occur

I am currently working on a form that includes a JavaScript submit function. Within the form, there are 3 anchor tags that I want to use to set different values to a hidden parameter when submitted based on the link clicked. Although the form submission w ...

Tips for accessing the HTML code of a TextBox in JavaScript while utilizing HTMLEditorExtender

Currently, I am utilizing the HTMLEditorExtender ajax tool on my website. The data is being saved in HTML format into the database and then retrieved within my project without any issues. However, there is a setback that I have encountered... When attemp ...

Issues arise when trying to render a component in React after importing the react-bootstrap library

After running npm init and installing react, react-dom, bootstrap, and react-bootstrap packages, I encountered an issue while trying to import components from the react-bootstrap library. The code import Button from 'react-bootstrap/Button'; resu ...

Storing the selected value from a dropdown box in PHP

Can anyone help me with echoing the $row['price'] based on the user's GPU selection? Your input is greatly appreciated! #adding more content to meet word count requirements. <div id="content"> <table border="1" style="width: ...

Creating an Ajax Post request for API invocation

I'm currently setting up an Ajax Post request to interact with an API. Here is a mock curl command for reference: curl -X POST \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --h ...

Ways to bypass mongoose schema validation while making an update request in the API

In my model, one of the fields is specified as providerID: { type: Number, required: true, unique: true }. The providerID is a unique number that is assigned when inserting provider details for the first time. There are situations where I need to update ...