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

Tips for maintaining the chat scroll position while typing on mobile devices

Check out this example page: https://codesandbox.io/s/summer-flower-uxw47?file=/index.html:4175-4223 The issue at hand is that when accessing the site from a mobile device and tapping on the input field, the keyboard pops up. This causes the text in the m ...

Displaying various images within a bootstrap modal window

I'm facing an issue with my gallery. It contains small images, and when a user clicks on a thumbnail, a modal should open with the full-size image. The problem is that even though I have the full-size images stored in the "/uploads/" folder and the th ...

Automatically generate numbering for an AngularJS ng-repeat list

I'm working on creating a student report list using Angularjs ng-repeat. My main issue is figuring out how to dynamically append numbering like an ordered-list to the generated list in the view. I am aiming for something similar to this: # | Name of ...

The server appears to be up and running, however there seems to be an issue when attempting to access the API as it is returning an Error: connect ECONNREFUSED 127.0.0.1

Trying to decouple app and server. Successfully running, but encountering Error: connect ECONNREFUSED 127.0.0.1:3000 in Postman when hitting "app.get('/')" API despite making necessary changes. In ./routes/users.js const express = requ ...

Jquery function for determining height across multiple browsers

I am currently facing an issue with setting the height of table cells in my project. While everything works smoothly on most browsers, Firefox seems to add borders to the overall height which is causing inconsistency across different browsers. If anyone k ...

Include the script tags retrieved from an array

I'm exploring the idea of dynamically adding JavaScript to the DOM using an array and a loop. The goal is to load each script sequentially, starting with scripts[0], then scripts[1], and so on. var myScripts = [["external", "https://code.jquery.com/j ...

I am attempting to retrieve the bot's permissions in order to validate if the command is authorized to execute

To verify if a command can be executed, I am attempting to retrieve the bot's permissions. Here is the code snippet I am using: let botid = "idbot" let bot = client.users.cache.get(botid) if (!bot.permissions.has("ADMINISTRATOR")) ...

Receive real-time price updates from Next.js using GetServerSideProps data

I'm currently working on fetching live bitcoin prices from CoinGecko. In my index.js file, I have an async GetServerSideProps function that is functioning correctly. The returned props are then passed down to the <Home /> component, and subseque ...

Combining PageObjects with non-angular pages: is it possible?

I am currently working on writing protractor tests for our application. One specific challenge I have encountered is dealing with a non-angular page within an angular page as an iframe. The issue I am facing is that I cannot properly map fields from the n ...

Troubleshooting issues with JavaScript events in order to effectively implement popovers

I am facing an issue on a webpage that contains a significant amount of JavaScript. The Twitter bootstrap's popover widget is not functioning as expected. Specifically, when I hover over the icon that should trigger the "popover," nothing happens. I h ...

How can one ensure the preservation of array values in React?

I'm struggling to mount a dynamic 'select' component in React due to an issue I encountered. Currently, I am using a 'for' loop to make API calls, but each iteration causes me to lose the previous values stored in the state. Is t ...

What steps should be taken to resolve the error message "EROFS: read-only file system, attempting to open '/var/task/db.json'?"

const jsonServer = require('json-server') const cors = require('cors') const path = require('path') const server = jsonServer.create() const router = jsonServer.router(path.join(__dirname, 'db.json')) const middlewa ...

Having trouble retrieving a value from the $http promise, causing the code within the then() function to not run as expected

In the past, I encountered a challenge with the $http service which I managed to solve by creating a dedicated service for handling my requests. However, as my requests grew larger, this solution started to seem inefficient. Instead of just assigning a sim ...

Issue with child component not reflecting changes when the state is updated

In an attempt to pass a value to a child component, I am encountering an issue where the value does not update when the parent component's value changes. Below is my code: Child Component: class Test extends Component { constructor(props) { su ...

Steps for integrating a universal loader in Angular

My implementation of a global loader is as follows: In the CoreModule: router.events.pipe( filter(x => x instanceof NavigationStart) ).subscribe(() => loaderService.show()); router.events.pipe( filter(x => x instanceof NavigationEnd || x in ...

When trying to load AJAX, it does not function properly unless the page is refreshed

I'm currently working on a web page and encountering some difficulties. Within my HTML, I have two divs that are refreshed using AJAX. The issue is that the content loading seems to be inconsistent unless I manually refresh the page or implement a tim ...

Is there a way to modify the window's location without having to reload it and without resorting to any sne

Initially, I believed that the hash hack was a necessity, but after observing the recent updates from Facebook, my perspective has shifted. The original hash hack (not certain if this is the correct term) involved changing location.hash to save a state in ...

Modify all the content within the DIV using Regex, while keeping the HTML tags intact

I am attempting to replace all the text inside a DIV, including within its children, without modifying any HTML tags. Specifically, I want to switch all instances of 'Hello' to 'Hi'. Thank you for your help. var changes = $('div ...

Finding the maximum value among multiple variables in AngularJS

After performing calculations, I have assigned specific values to variables. console.log("Gain_weight is "+ Gain_weight); console.log("Gain_smoking is "+ Gain_smoking); console.log("Gain_exercising is "+ Gain_exercising); console.log("Gain_foodhabits ...

What methods and technologies are accessible for executing JavaScript through PHP?

Are there any frameworks or tools available to execute JavaScript from PHP? Is there a similar project like the Harmony project for PHP? I am interested in running JS unit tests (or even BDD) directly from PHP, as demonstrated in this post (for Ruby). Am ...