Split the outcome and its handling into individual files

My script requires me to make an XML request, receive the response from the server (if resolved), parse it, and store the parsed result in a variable.

Only after this process can I proceed with various tasks.

To achieve this separation of concerns, I aim to:

  • Encapsulate the above process into a function in an external script that can be called when necessary.
  • Avoid having all my code within a .then() method.
  • Organize my code into logical files, each dedicated to a specific task.

I have come up with a sample piece of code to illustrate my requirements. However, as I am relatively new to asynchronous programming, I wonder if it is acceptable to structure my code in this manner, considering that the response should be resolved quickly in my scenario.

If this approach is suitable, I plan to place this code snippet in a separate file for easy importing and calling of the function testing() (or whatever its name may be) from any part of my project.

function delay(input) {
    return new Promise(function(resolve, reject) {
        // perform some async operation here
        setTimeout(function() {
            // resolve the promise with a value
            resolve(input + 10);
        }, 500);
    });
}

function testing() {delay(5).then(result => {return document.write(result)})};

testing();

EDIT

Upon reviewing the insights provided by @DrewReese and the references in the comments, I believe I have identified the issue at hand.

The above code example was slightly misleading in conveying my intention, but I recognize that there might not be a straightforward solution. Consider the following code snippet (essentially similar to the previous one, except for the last three lines):

function delay(input) {
    return new Promise(function(resolve, reject) {
        // perform some async operation here
        setTimeout(function() {
            // resolve the promise with a value
            resolve(input + 10);
        }, 500);
    });
}

function testing() {delay(5).then(result => {return result})};

var test = testing();
document.write(test);

In this scenario, I understand that defining test results in 'undefined' since the Promise within testing() is yet to be resolved.

The challenge I face is: Is it possible to assign a value to test only once the Promise is resolved, without necessitating a then(), and potentially display a different output while waiting for resolution (such as "LOADING...")?

I am unsure if it is feasible to determine whether a variable holds a pending Promise and showcase two distinct values based on its state: awaiting resolution or already fullfiled/rejected.

I trust that my explanation is clear; otherwise, I will explore further and pose another question if required.

Answer №1

One of the main purposes behind promises, specifically promise chains, is to avoid descending into "nesting hell" by streamlining your sequence of actions. When a promise chain resolves blocks of code, it indeed returns a promise that can be acted upon using then. Here is an example to help clarify:

someAsyncHttpRequest(parameter) // <- Returns Promise
    .then(result => {
        // Perform operations on result data, such as extracting response data,
         mutating it, saving it, or executing other actions based on its value
        ...
        // You can also return a Promise
        return Promise.resolve(mutatedData);
    })
    .then(newData => {  // <- mutatedData is passed as a parameter
        // Process new data, and potentially reject
        let rejectData = processNewData(newData);
        return Promise.reject(rejectData);
    })
    .catch(err => {
        console.log('Any caught promise rejection regardless of its origin:', err);
    })
    .finally(() => {// Execute this code no matter what});

If you require access to variable values set within the chain, you must make the outer function asynchronous and await the completion of the promise chain:

asyncFunction = async (parameter) => {
    let asyncValue;
    
    await someAsyncHttpRequest(parameter)
        .then(result => {
            ...
            asyncValue = someValue;
            ...
        });
    // asyncValue is now safe for use
};

For instance, in your situation:

function delay(input) {
    return new Promise(function(resolve, reject) {
        // Perform an asynchronous operation here
        setTimeout(function() {
            // Resolve the promise with a specified value
            resolve(input + 10);
        }, 500);
    });
}

**async** function testing() { // Declare this as an asynchronous function
    let value = **await** delay(5); // Now awaiting the resolution of the Promise
    console.log(value); // Outputs the resolved value of 15!
    return value; // Simply returns the resolved Promise
}

var test = testing();

console.log(test); 
/** Outputs the Promise!
   Promise {<pending>}
     __proto__:Promise
     [[PromiseStatus]]:"resolved"
     [[PromiseValue]]:15
*/

test.then(console.log)); // Outputs the returned resolved value, which is 15

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

Leveraging Facebook Pixel within a DNN-powered website

Is there a way to integrate the Facebook pixel into a website created using the DNN platform? ...

What is the most effective method for detecting the conclusion of a wheel event in JavaScript?

Is there a way to trigger an event once my wheel event has finished? I came across a solution that uses a scroll event (which is similar) with a setTimeout function here: However, I'm curious if there's a more elegant method to detect when my w ...

By implementing JavaScript formulas into a CSV file for importing into Google Sheets, the outcome is the creation of numerous columns

I have been struggling to insert the following formula into a single column in Google Sheets using JavaScript, but it keeps appearing in different columns due to the presence of commas. =IF(A2="VALID", B2, 0) Currently, I am utilizing the code ...

What is the best way to continuously swap out images inside a div every second, except when the mouse hovers over

I recently posted a question on Stack Overflow about displaying an image in a div when a specific link is hovered over, and thanks to the help of user adeneo, I was able to find a solution (jsFiddle): HTML Markup: <div id="imgs"> <img src="h ...

Is there anyone out there who has successfully imported a model from the three.js editor?

As a designer and 3D artist who occasionally delves into coding, I have a question regarding loading a model from the three.js editor into an actual web page. Despite my limited programming knowledge, I've tried various methods to achieve this, includ ...

Steps to save HTML canvas artwork as an image with the click of a button

I'm encountering some difficulties with this task, despite my extensive search for solutions. I have attempted to implement code snippets from various sources online, but they don't seem to work when integrated into my own code. My objective is ...

JavaScript - Assigning a class to an element based on an array

I am facing a challenge where I need to assign classes from an array to an element in sequential order. The issue is that once I reach the end of the array, I do not know how to loop back to the beginning and start over. Here is my current code: var bac ...

Trouble with Callback firing in Select2's 'Infinite Scroll with Remote Data' feature

After reviewing the tutorial on the Select2 project page, I am implementing a feature to load additional records as the user scrolls to the end of the results. <script> $(document).ready(function() { $('#style_full_name').select2({ ...

What is the best way to trigger a Quasar dialog from an outside component?

Currently, I am working with Vue.js 2.x + Quasar 1.x using http-vue-loader (no build tools required). I have placed a q-dialog in a separate component named MyComponent. However, when I try to include it in a parent component like this: <my-component&g ...

Issue with Material-UI tab not showing the component upon page load

After setting up material-ui tabs with react-router, I encountered an issue where only the tab names Tab A and Tab B are displayed upon page render. The desired behavior is for the TabAReport component to be automatically rendered without requiring user in ...

Is it possible for the *ngIf directive to stop unauthorized users from accessing my admin page through their browsers?

When the *ngIf directive is set to false, a certain element or component will not be included in the DOM. For example, let's say there is a component that displays admin tools and should only be accessible to authorized users (administrators). Will se ...

There is no overload that fits this call. The string type cannot be assigned to the Signals type

Lately, I've been utilizing Typescript for constructing a microservice and managing signals. The code was running smoothly until a few days back, but now it's throwing errors without any apparent fix. This is an excerpt of the code responsible f ...

Find Discounts Array

Is there a way to determine the Array of Discounts based on the Base Price initially and then calculate them against the Amount After Discount? In the image provided below, we have the Base Price. This base price may include multiple discounts. Each disc ...

securely load HTML form with data stored in MySQL

I have developed a basic HTML/JS math form for performing calculations. To simplify the form, I made it more concise for clarity: function output(){ var value1 = document.getElementById('value1').value; var ...

Using Ajax to send a JSON object containing two arrays to a servlet, then parsing it in a Java servlet without the use

When sending data to a servlet, I utilize an Ajax POST call to send a JSON object containing two arrays. In the servlet class in Java, I need to read this data sent in two lists or arrays. I am avoiding the use of jQuery for the Ajax call and am not very f ...

When there is an infinite loop in the run block, the $http success callback in the factory is not triggered

Take a look at my code with the relevant parts highlighted: authorization.js while loop is omitted, I encounter this error:</p> Cannot read property 'toString' of undefined This error stems from attempting to call toString on currentUse ...

Enhance Woocommerce searching functionality by incorporating personalized user information in the order filter for registered customers through Ajax search

I am looking to incorporate a user's unique meta data labeled 'sageaccountnumber' into the 'filter by registered customer' section of the WooCommerce orders list, as illustrated below: https://i.sstatic.net/lzVKZ.jpg The PHP code ...

Basic library using babel, TypeScript, and webpack - Error: (...) is not a recognized function; within Object.<anonymous>

Recently, I encountered a strange issue while trying to bundle a simple function using babel, typescript, and webpack. You can find the example that is not working at this link. To test it, simply download the code, run npm/yarn install, npm/yarn run buil ...

Utilizing jQuery in Wordpress to Toggle Content Visibility

Currently, my website pulls the 12 most recent posts from a specific category and displays them as links with the post thumbnail image as the link image. To see an example in action, visit What I am aiming to achieve is to enhance the functionality of my ...

Error Encountered: Attempting to access the 'play' property of an undefined object caused a TypeError

I recently tried my hand at creating avatars and animations using readyplay.me and mixamo. For those interested, you can check out the tutorial I followed here: https://dev.to/nourdinedev/how-to-use-threejs-and-react-to-render-a-3d-model-of-your-self-4kkf ...