Passing an array to a view is not possible when working with asynchronous methods

I am currently working on developing a Dapp that is connected with the Ethereum Blockchain. Within this project, I have created a JavaScript function that invokes asynchronous methods.

async function getFiles(id, array){
    if(id < 2){
        myContract.consultFile.call(id,"0x2b461Db580028F263351B969cFd8542db696787E",function(err, res){
            array.push({title : res[0], description : res[1]});
            getFiles(++id, array);
        });
    }
    return array;
}

Do you think this initial function should be asynchronous?

In addition, I have a helper function that calls the aforementioned one. I have made some attempts but it is returning a promise object.
After using console.log(), I can see that the [[PromiseValue]] is correct.
However, when trying to display it in my view using {{#each files}} with the code below, nothing seems to happen. If I return tmp, I see [Object Promise].
Is the array being successfully sent? How can I properly display the array?

Template.myDocuments.helpers({
    'files': function(){
        var tmp = getFiles(0,[]);
        tmp.then(function(val){
        console.log(val);
        return val;
    });
    }
});

Answer №1

function initiateFileDisplay(callback){
    callback(0,[]);
}

function retrieveFiles(id, array){
    while(id++ < 2){
         myContract.consultFile.call(id,"0x2b461Db580028F263351B969cFd8542db696787E",function(err, res){
        array.push({title : res[0], description : res[1]});
    }
    console.log(array);

}
initiateFileDisplay(retrieveFiles);

The provided code is designed to run the async function properly using callbacks, which ensure that the asynchronous call completes successfully before proceeding with the execution of code following the callback. Although the callback is asynchronous and doesn't allow for returning values to synchronous functions, having the array declared globally should retain the desired value after calling initiateFileDisplay(retrieveFiles).

For a more comprehensive understanding of callbacks and asynchronous programming in JavaScript, you may find this resource helpful.

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

When attempting to execute "nodemon," the command was not detected

When trying to use 'nodemon' in the command line, an error occurs stating that it is not recognized as a cmdlet, function, script file, or operable program. The system suggests checking the spelling of the name and verifying that the path is corr ...

Incorporating a dropdown menu into an HTML table through jQuery proves to be a

I loaded my tabular data from the server using ajax with json. I aimed to generate HTML table rows dynamically using jQuery, with each row containing elements like input type='text' and select dropdowns. While I could create textboxes in columns ...

Despite implementing componentDidMount, the setState function is failing to update an initialized array state property

I have checked out similar questions such as : Why isn't this.setState updating the state property? Issue with this.setState not updating state Understanding that setState operates asynchronously is key. This snippet showcases my code: import Rea ...

Using two variables for iteration in Vue.js v-for loop

Can you create a v-for loop with two variables? I attempted the following, but it did not function as expected <ul id="example-1"> <li v-for="apple in apples" v-for="banana in bananas"> {{ apple .message }} {{ banana .message }} & ...

An optimal method for retrieving data from a database using an array

I am facing a performance issue with querying my database using an array of about 400 single string number items. The current implementation takes around 4-6 seconds to load the page, which is not efficient. I am looking for a better way to handle this s ...

Utilizing ng-click within a tooltip

I've implemented Angular Bootstrap UI and successfully added a tooltip to my project. Snippet of HTML: <div ng-app="helloApp"> <div ng-controller="helloCtrl as hello"> <a tooltip-trigger="click" tooltip-placement="bottom" uib-t ...

In Firefox, the HTML label fails to activate the corresponding input field when the mouse is moved while clicking

If you click on the label in the example below, it will change the state of the input. document.querySelector("label").addEventListener("click", function() { console.log("clicked label"); }); label { -webkit-user-select: none; -moz-user-select: no ...

Having trouble retrieving the URL from JSON data - every time I attempt to access it, it just shows as undefined. Any suggestions

Having trouble extracting the URL from JSON, as it shows undefined. Any suggestions? <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta> <script language="JavaScript" type="text/javascript" ...

Creating a platform for users to share their thoughts and engage in

A friend and I are working on creating a commenting system for our website. We have written some code to insert values into a mysql database so that they can be read and displayed as comments later on. Unfortunately, we are facing an issue where the data i ...

Bring in the content to Notepad utilizing jQuery

How can I export data to Notepad? I have fields for Name, Age, and WorkingStatus that are input as text and textarea. Is there a demo or code available to help me insert this data into Notepad? ...

What is the best way to dynamically showcase options in a React application?

product.js Qty: <select value={qty} onChange={(e) => { setQty(e.target.value) }}> {[...Array(product.countInStock).keys()].map((x) => ( <option key={x + 1} value={x + 1}> ===> I need to dynamically display options b ...

Utilizing the map function to display elements from a sub array

I'm struggling to print out the comments using the map function in this code: class Postcomment2 extends React.Component { uploadcomment = () => { return this.props.post.comments.map((comment) => { return <div>{comment["comment"]}< ...

Resolve problem with npm peerDependencies for specific package

One issue my application is facing involves a set of domain packages that all have the core as a peer dependency. The structure of these domain packages is as follows: "name": "domain-a-pckg", "peerDependencies":{ "core-p ...

Experience the power of TypeScript in a serverless environment as you transform your code from

I have some JavaScript code that needs to be converted to TypeScript. Currently, I have two files: API_Responses.js const Responses = { _200(data = {}) { return { statusCode: 200, body: JSON.stringify(data), }; } }; module.export ...

How can you turn off CSS3 animations for browsers that don't support them

Upon page load, a fade-in animation is applied to the main container. Although it functions properly in most browsers, it seems to have an issue in IE(9). Is there a method to identify if the user's browser does not support CSS3 animations and disabl ...

The presence of a 'foreach' loop is leading to dysfunction in my function

I am currently working on the following code: <?php $item1 = A; $item2 = B; $item3 = C; $array = array($item1, $item2, $item3); function myFunction () { if ($item = "A") { echo "Alpha "; } elseif ($item = "B") { echo ...

The Array Result of a WordPress WP_Query

I need assistance with modifying my WordPress homepage to display only 2 blog posts, each with a different floating element - one on the left and one on the right. In native PHP, I can easily fetch results as an array and print them using $result[0] and $r ...

Adding an await tag to dispatch causes issues with performing a react state update on an unmounted component

I recently added an await tag to a redux dispatch and now I am encountering the following error message: index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your applica ...

Is it possible to add items to a JS object that isn't an array?

Here is an example of the object I am working with: { "_id": "DEADBEEF", "_rev": "2-FEEDME", "name": "Jimmy Strawson", "link": "placeholder.txt", "entries": { "Foo": 0 } } To access this data in my JavaScript code, I use a $.getJSON call. ...

"Improvements required for the search and filter functionality in the JSON

My JSON function retrieves image data and displays it in panels. Here is an example of the code: $.getJSON('iproducts.json',function(products){ var output = ""; $.each(products.appleitems, function(i, product) { output += "<di ...