What can be done to ensure that the value from a promise is retained and available for use in

Currently, I am executing a database query and then manipulating the data to obtain a single numeric value. This value is essential for use in a subsequent array.

The current definition of the array appears as follows (see below). The issue at hand is that all_kdm_coverage is a promise. However, what I require is to extract the numeric value from this promise.

const scrolls = [
    {
        title: "Kadena de Mano",
        link: "./Kdm",
        coverage: all_kdm_coverage
    },
]

For additional context, here's an extended snippet:


async function GetCoverage(scroll_path) {
    const apiName = 'foo';
    const path = '/scrolls/' + scroll_path;
    const myInit = {
        headers: {},
        response: false,
    };
    const response = await API.get(apiName, path, myInit)
    console.log('response:',response)
    return response.Items
}

function GetScroll(scroll_name, scroll_array) {
    const scroll_data = scroll_array.find(scroll => scroll.Scroll === scroll_name);
    console.log('scroll_data:',scroll_data)
    return scroll_data
}

let dataGlobal;
const getData = () => (dataGlobal ??= GetCoverage("all"));

const all_kdm_coverage = getData().then(
    (data) => {
        const  kdm_entry = GetScroll("kdm", data)
        const coverage = kdm_entry.Coverage
        console.log('kdm coverage:',coverage)
        return coverage
    }
)

const scrolls = [
    {
        title: "Kadena de Mano",
        link: "./Kdm",
        coverage: all_kdm_coverage
    },
]

// To demonstrate how the scrolls array is utilized 
export const DanzanRyuCollection = () => {
    return (
        <>
            <h1 className="h1_index">Scrolls</h1>
            <Collection
                type="list"
                items={scrolls}
                gap="1.0rem"
                alignItems="center">
                {(item, index) => (
                    <ScrollCard
                        key={index}
                        padding="1rem">
                        <Link href={item.link}>
                            {item.title}
                        </Link>
                        <Rating ratings={[item.coverage]}/>
                    </ScrollCard>
                )}
            </Collection>
        </>
    );
};

What strategy should be employed to define the coverage: value in scrolls?

Update: It has been suggested to do the following:

const scrolls = [
    {
        title: "Kadena de Mano",
        link: "./Kdm",
        coverage: await all_kdm_coverage
    },
]

However, attempting this results in the following error message indicating it is experimental and not fully supported:

Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enable it)
Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enable it)
console.error @ client.js:1
window.console.error @ next-dev.js:27
overrideMethod @ react_devtools_backend_compact.js:2367
handleErrors @ hot-dev-client.js:131
processMessage @ hot-dev-client.js:202
eval @ hot-dev-client.js:50
eval @ websocket.js:58
handleMessage @ websocket.js:57

Answer №1

To elaborate on the feedback given by Bergi

let scrolls = [];
all_kdm_coverage.then(coverage => { 
 scrolls.push({ 
   title: "Kadena de Mano",
   link: "./Kdm", 
   coverage, 
  }) 
}) 

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

Creating a TypeScript class with methods to export as an object

Just dipping my toes into Typescript and I've encountered a bit of a challenge. I have a generic class that looks like this: export class Sample { a: number; b: number; doSomething(): any { // return something } } My issue ari ...

What prevents me from extending an Express Request Type?

My current code looks like this: import { Request, Response, NextFunction } from 'express'; interface IUserRequest extends Request { user: User; } async use(req: IUserRequest, res: Response, next: NextFunction) { const apiKey: string = ...

What is the process for refreshing a user's session from the backend following updates to their metadata?

Currently, I am utilizing Next.js on the client side, auth0 for authentication, and Django Rest Framework for the backend. By following Auth0's Manage Metadata Using the Management API guide, I successfully managed to set new metadata values (verified ...

Navigate through set of Mongoose information

I have a challenge where I need to retrieve an array of data from Mongoose, iterate through the array, and add an object to my Three.js scene for each item in the array. However, when I try to render the scene in the browser, I encounter an error that say ...

Transferring data using a JavaScript enhanced form

I'm currently working on a search page that showcases results in a table format. I am looking to enhance the functionality using Javascript. The table is contained within a form, and each row offers multiple actions, such as adding a comment. While I ...

Upload a user-sent image to a remote SFTP server for safekeeping

Can someone help me figure out how to upload a file to an SFTP remote server using ssh2-sftp-client? I am trying to retrieve the file from the user via a post request along with the destination. To process the file, I am utilizing multer. const Client = r ...

acquiring JSON information from different domains

I am in need of creating an ajax request to fetch JSON data from a RESTful Web Service that is hosted on a different domain (KARAF using cxf). The client making the ajax call is situated on a separate domain (Apache Tomcat). The Web Service responds with ...

Accessing props in setup function in Vue 3

I am encountering issues when trying to access the props value (an array) in my composition API setup. The component I have is called DropDown, and I am passing it an array of objects. Here's what I need to achieve: export default { emits: ['up ...

What is the best way to retrieve the overall error status from the Material UI DataGrid?

I am currently utilizing the Material UI DataGrid element to display information from an EXCEL file. Each Excel document consists of numerous column titles with specific types assigned to them. As an example: const columns = [ { "field&quo ...

What is the best way to interrupt an animation and restart it?

On my webpage, I have implemented some anchors and links that navigate to these anchors. When I click on a link, the background-color of the anchor changes. I use animation to gradually fade out this color over 10 seconds - starting with white and then rem ...

Search through a JSON object, identify all keys that start with the same letter, and transfer them to a new JSON data structure

I am looking to iterate through my JSON data and extract all keys along with their values that start with the letters "QM". Below is an example of my JSON content: [ { MHF46: 'Ledig', MHF181: '06', QM6_QMSI2: '1899-12-30 ...

Enhanced coding experience with JavaScript completion and ArangoDB module management

Exploring New Horizons After more than a decade of using Eclipse for Java development, I have decided to delve into the realms of javascript and arangodb due to high demand. My current task involves developing multiple microservices to run within arangodb ...

Is it possible to include a div above a centered image?

Currently I am working with ImageFlow and I would like to overlay a div on top of the image when it is clicked, sliding it into the center. I have been looking through the JavaScript file but the function MoveIT() seems to be called multiple times and I am ...

What approach can be taken to establish a dependency between an AngularJS controller and a value that is retrieved through ajax and loaded onto the root

I have an app that loads like this: app.js file: angular.module('App', []).run(['$rootScope', '$q', 'SessionManager', 'EndpointService', function ($rootScope, $q, SessionManager, EndpointService) { $r ...

Using the power of jQuery and Ajax to smoothly transition to a different page after editing the value of

Displaying a MySQL table named demo with the values Peter and John along with edit links Example Peter EDIT John EDIT When the edit link is clicked, it will open the page edit_name.php. In edit_name.php, you can update the clicked value using the updat ...

Mall magnitude miscalculation

I am currently experiencing an issue with Galleria and the Flickr plugin. Some images are displaying correctly, while others appear scaled and parts of them are cut off. How can I fix this problem? Below is the HTML code for the Galleria gallery on my web ...

Using Jquery to dynamically add an active class to a link if it matches the current URL

Is there a way to modify the code below so that only the exact current URL will have the active class added? Currently, even when the URL is http://localhost/traineval/training, it also adds the active class to http://localhost/traineval/training/all_train ...

JSON data being sent through an AJAX request

Currently, I am developing a chat system that automatically refreshes using AJAX. Initially, I utilized the jQuery $.post function which worked fine for my needs. However, since I required JSON data from my PHP script, I switched to using the $.ajax functi ...

Does adding the Angular bootstrap script at the end of the body tag impact webpage speed more than using ng-app on the body tag?

In the past, we had placed ng-app on the body tag which led to problems with dependency injection when multiple modules were being used on the same webpage. This required module creators to be aware of the existing app and inject their app into it. We are ...

Angular JS element cannot be located

My Angular object is not being passed when I write a new function, and I'm unsure why. The object, named person, is directly bound in the HTML and returns 2 items from the cardsCollection array. The function I'm attempting to create is called cl ...