After the child promise is resolved, have the parent function return a boolean value

I am currently faced with a challenge in my framework where the parent function must output either true or

false>. However, I also need to perform an asynchronous operation within that function.</p>
<p>How can I ensure that the parent function returns <code>true
or false after completing the async task?

An example of what doesn't work is as follows:

   function parent() {
     const child = new Promise();
     child.then(
       function (success) { return true },
     )
   }

The issue here is that the return statement is inside the context of the child.then() function.

Answer №1

To ensure smooth execution, it is essential that the parent function is also asynchronous. Failure to do so will result in blocking the main thread, which goes against best practices.

Follow this approach:

const parent = async () => {
    const childResponse = await child();
    if (childResponse === "something") {
        return true;
    } else {
        return false;
    }
};

Avoid doing this:

const parent = () => {
    let promiseResult, parentReturnValue;

    child.then(result => {
        promiseResult = result;
        if (promiseResult === "something") {
            parentReturnValue = true;
        } else {
            parentReturnValue = false;
        }
    });

    while (promiseResult === undefined) {
        // Main thread blocked
    }
    
    return parentReturnValue;
};

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

Is there a simpler way to retrieve data from PHP or to efficiently filter the data once it's been retrieved?

Creating a business directory website involves fetching data from a database. The issue arose when attempting to apply a function uniformly to all boxes, as only the first one with the specified id would function correctly. To address this problem, the fol ...

Generate a fresh object if the values within the TypeScript object are identical

How can I filter an object to return a new object containing elements with the same values? For example: allValues = {"id1": 3, "id2": 4, "id3": 3} The desired output is: filteredValues = {"id1": 3, "id3": 3} This is because the keys "id1" and "id3" hav ...

Emphasize any word starting with an @ symbol to highlight its importance

My goal is to enhance the appearance of words that begin with an "@" symbol by making them bold. For example, transforming the sentence: '@xyzharris has a cat @zynPeter' into: '@xyzHarris has a cat @zynPeter' ...

Learn how to eliminate all text characters from a string using jQuery, leaving only the numerical values behind

My webpage features a variety of different products, each with their own values. When trying to calculate the total sum of these products and display it in the shopping cart, I encountered an error displaying NaN. How can I remove this NaN from the strin ...

Unable to establish connection with server through Ajax request on HTML page

I set up a NodeJs server using the Express module. However, I am facing issues with implementing an AJAX request from an HTML page using $.ajax when clicking a button. I want to retrieve data from the server in either JSON or text format but for some reaso ...

How can I retrieve a variable in a JavaScript AJAX POST request?

Similar Question: How to retrieve a variable set during an Ajax request I am facing a challenge, as I am making an ajax call and receiving a number as the response. My query is, how can I assign this returned number to a variable that is accessible ou ...

What could be causing my table to appear multiple times in the HTML when using jQuery?

Using Jquery to dynamically return a list of products, render it as HTML, and show it on the page using $(selector).html(html), I've encountered an issue. When adding products to the cart too quickly, which triggers the rendering of the cart again, th ...

Issue encountered with Ionic and Angular 2: Denied application of style from 'http://localhost:8100/build/main.css' due to unsupported MIME type ('text/html')

Initially, everything was going smoothly with my Ionic build, but things took a turn when I tried to test it on my iPhone. After stopping the server and running ionic serve --address localhost, I noticed that my stylesheet wasn't loading. Even after r ...

JSLint error: Inconsistent use of spaces and tabs detected

I recently ran the code below through JSLint: $(document).ready(function() { /* Insert paragraph upon page load */ // Retrieve all header elements var header = document.getElementsByTagName('h1'), parent, ...

Plugin refresh after callback

I have a webpage that features a row of buttons at the top, followed by some content below. Whenever one of the buttons is clicked, the content is updated using UpdatePanels. Within this content, I am attempting to incorporate the royal slider plugin, wh ...

Is there a way to position the menu above the button?

I need some help with my menu. Currently, it is showing up below the button and within my footer instead of above the content like I want it to. If anyone can assist me in understanding what I am doing wrong, I would greatly appreciate it. Thank you for ta ...

LeafletJS and ReactJS integration causing misalignment in tile ordering

In my ReactJS single page application, I am utilizing the LeafletJS plugin to showcase a full-page map. Even after following the guidelines mentioned here, I am facing an issue where the map tiles are not displayed in the correct order and appear to be shu ...

Error message: The Bootstrap .dropdown() method failed because it encountered an "Uncaught TypeError: undefined is not a function"

I've encountered an issue that seems to be a bit different from what others have experienced. Despite trying various solutions, I still can't seem to fix it. I suspect it might have something to do with how I'm importing my plugins. The erro ...

Arranging Data in AngularJS based on Selected Filter Criteria

I have a filter function that currently only returns the name values in my table. I would like to add options for both ascending and descending sorting to this filter. Progress So Far: I am able to retrieve values from all inputs, including the name and ...

Use the npm-search feature to show only the name and description columns in the search results

After running the command npm search packagename, I noticed that the results are shown in 6 columns: name, description, author, date, version, and keywords. Is there a way to customize npm-search so that it only displays the name and description columns? ...

Change the left position of the sliding menu in real-time

I am currently designing a website with a sliding menu feature. By default, the menu is set to -370px on the left, displaying only the "MENU" text initially. When a user hovers over the menu, it expands to the right, allowing them to select different menu ...

React ensures that the page is not rerendered until after data has been fetched

I am dealing with the following code snippet. This is my React hook: const [isLoading, setIsLoading] = React.useState(true); useEffect(() => { setIsLoading(() => true); // I expect the page to rerender and display loading now. const select ...

Unable to call an object that may be 'undefined': Utilizing a function with a return object that includes asynchronous functions as properties

I have a function exported in my adapter.ts file: import type { Adapter } from "@lib/core/adapters"; export default function MyAdapter (): Adapter { return { async createUser (user: User) { ... }, async findUserByEmail (email ...

Adding hyperlinks that do not redirect

I have 2 separate divs displayed on a website: <button class="form-control margin btn btn-warning hide_all" id="addLinks">Link Pages</button> <button style="display: none" class="form-control margin btn btn-primary hide_all" id="hideLinks"& ...

What is causing the most recent iPhones to have issues with my Javascript code?

After analyzing my webserver logs, it appears that an iOS 14 device is categorizing one of my Javascript files as "injected". This file seems to be operating in a separate environment or namespace. As a result, any AJAX attempts made by the script fail bec ...