Cannot find a function within the Promise

Here is the code snippet I am working with:

var c = function(address, abiJson){
    var _ = this;
    this.data = {
            wallet: false,
            account:{
                address: false
            },
            contract:{
                address: address
            }
    };
    this.abi = $.getJSON(abiJson, function(abi){
        _.data.abi = abi;
        if(typeof web3 !== 'undefined'){
            window.web3 = new Web3(web3.currentProvider);
            window.cont = web3.eth.contract(abi).at(address);
        }
    });
    this.getData = function(cb){
        if(typeof _.data.abi !== 'undefined'){
            _.updateData.done(() => {
                cb(_.data);
            });
        }
        else{
            _.abi.then(() => {_.updateData
            })
            .done(() => {
                cb(_.data);
            });
        }
    }
    this.updateData = Promise.all([
            _.get('x'),
            _.get('y')
        ])
        .then(values => { 
            _.data.x.y= values[0];
            _.data.x.z= values[1];
        })
        .then(() => {
            Promise.all([
                _.get('v', 1),
                _.get('v', 2),
            ])
            .then(values => {
                _.data.y = values;
            });
        });
    this.get = function(method, args){
        return new Promise(function(resolve, reject) {
            window.cont[method](args, function(error, result){
                if(!error) resolve(result);
            });
        });
    }
}

I have encountered an issue where when I call the function

_.get('x').then((x) => console.log (x))
outside the updateData function, all the data is retrieved successfully. However, when I utilize the getData function, errors are thrown for all the get functions stating that _.get is not a function.

I am struggling to identify where I may have made an error in my implementation. This is my first time working with JavaScript Promises.

Answer №1

Below is a condensed version of the question:

var C = function(address, abiJson){
    var _ = this;
    this.updateData = Promise.all([
            _.get('x'),
            _.get('y')
        ]);
    this.get = function( arg){ return Promise.resolve( arg)};
}
var c = new C();
c.updateData.then( values => console.log(values)); 

When calling get within the array initializer argument of the Promise.all call, an error occurs because get has not yet been added as a method of _ (which is assigned to this). The immediate problem can be resolved by adding the get method before creating the array:

var C = function(address, abiJson){
    var _ = this;
    // add get method first:
    this.get = function( arg){ return Promise.resolve( arg)};
    this.updateData = Promise.all([
            _.get('x'),
            _.get('y')
        ]);
}
var c = new C();
c.updateData.then( values => console.log(values)); 

Answer №2

_ variable is not valid in this context. It can be used as a function but not when creating an object. To maintain scope, you can use bind for regular functions. Arrow functions automatically retain the current scope. Here is an example code where _ has been replaced with 'this' and binded to the callback of getJSON. If arrow functions are used, bind is not necessary.

var c = function(address, abiJson){
    this.data = {
        wallet: false,
        account:{
            address: false
        },
        contract:{
            address: address
        }
    };
    this.abi = $.getJSON(abiJson, function(abi){
        this.data.abi = abi;
        if(typeof web3 !== 'undefined'){
            window.web3 = new Web3(web3.currentProvider);
            window.cont = web3.eth.contract(abi).at(address);
        }
    }.bind(this));
    
    this.getData = function(cb){
        if(typeof this.data.abi !== 'undefined'){
            this.updateData.done(() => {
                cb(this.data);
            });
        }
        else{
            this.abi.then(() => {this.updateData})
            .done(() => {
                cb(this.data);
            });
        }
    }
    
    this.get = function(method, args){
        return new Promise(function(resolve, reject) {
            window.cont[method](args, function(error, result){
                if(!error) resolve(result);
            });
        });
    }
    
    this.updateData = Promise.all([
        this.get('x'),
        this.get('y')
    ])
    .then(values => { 
        this.data.x.y= values[0];
        this.data.x.z= values[1];
    })
    .then(() => {
        Promise.all([
            this.get('v', 1),
            this.get('v', 2),
        ])
        .then(values => {
            this.data.y = values;
        });
    });

}

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

Transmitting intricate Javascript Array to ASP.NET Controller Function

I am facing an issue with sending a complex JavaScript array to my asp.net mvc6 controller method. I have tried two different methods to pass the data, but neither seem to be working for me. public IActionResult TakeComplexArray(IList<ComplexArrayInfo ...

Send image data in base64 format to server using AJAX to save

My goal is to store a base64 image on a php server using the webcam-easy library (https://github.com/bensonruan/webcam-easy). I added a button to the index.html file of the demo: <button id="upload" onClick="postData()" style=" ...

Tips for transferring an item to PHP

I am facing a challenge in sending data from the client side (javascript) to the server (php) using ajax. My object structure is as follows: sinfo={ topic_title:title, topic_id: tid, section_name:section_name, ...

Exploring date formatting in NestJs with Javascript

Currently, I am working with a ScrapeResult mikroOrm entity. I have implemented the code newScrapeResult.date = new Date() to create a new Date object, resulting in the output 2022-07-17T17:07:24.494Z. However, I require the date in the format yyyy-mm-dd ...

Is there a way to utilize a JavaScript function to transfer several chosen values from a select listbox to a different listbox when a button is clicked?

Is it possible to create a functionality where users can select multiple values from a first list and by clicking a button, those selected values are added to a second list? How can this be achieved through JavaScript? function Add() { //function here ...

Retrieve data using Ajax querying from a specific data source

Currently, I am attempting to construct a custom query using Ajax to interact with PHP/MySQL. Here is what I have so far: Javascript code: var i=2; fetchFromDBPHP("name", "tblperson", "id="+i); function fetchFromDBPHP(column, table, condition) { ...

The `forEach` method cannot be called on an undefined node.js

I have been developing a small study website but encountered an issue with the title. Despite extensive internet research, I have not been able to find a solution. The system I am using is Ubuntu with node.js, express, and mysql. app.js var fs = requir ...

"Troubleshooting a problem with Mongoose's findOne.populate method

There is an array of user IDs stored in the currentUser.follow property. Each user has posts with a referenceId from the PostSchema. I am trying to populate each user's posts and store them in an array called userArray. However, due to a scope issue, ...

Angular JS - Selecting Directives on the Fly

I'm currently developing an application where users can choose from various widgets using a graphical user interface (GUI). My plan is to integrate these widgets as angular directives. THE CONTROLLER $scope.widgets = ['one', 'two' ...

Using AJAX to pass the ID name when clicking in PHP

Currently, I am in the process of implementing an Ajax-driven filtered search system that consists of three distinct tabs. These tabs allow users to search by names, category, and location. I have successfully enabled searching when a user types a name int ...

The next/font feature functions perfectly in all areas except for a single specific component

New Experience with Next.js and Tailwind CSS Exploring the next/font Package Delving into the realm of the new next/font package has been quite interesting. Following the tutorial provided by Next.js made the setup process smooth sailing. I've incorp ...

How is the server architecture typically designed in a node.js application?

Currently, I am developing a node.js application using socket.io and I'm seeking advice on how to structure the folders properly. The files that I have in my project include: Server.js package.json Additionally, I have: Client.js Index.html Incl ...

What is it about Kyle Simpson's OLOO methodology that seems to swim against the tide of Typescript's popularity?

Disclaimer: this post might come across as impulsive. Warning for Typescript beginners! Also, a bit of a vent session. Recently, I delved into the OLOO approach from the YDKJS book series within a Typescript and Node environment. // ideal JS syntax le ...

Search timeout restriction

I have a function that makes a request to the server to retrieve data. Here is the code for it: export default class StatusChecker { constructor() { if (gon.search && gon.search.searched) { this.final_load(); } else { this.make_req ...

A common challenge in React is aligning the button and input line on the same level

I'm currently working on a React page where I have an input field and a button. My goal is to align the bottom edge of the button with the bottom line of the input. Here's the code snippet I have: `<form className='button-container'& ...

Steps for triggering a re-render in a React component when an external value changes

I am currently working on a project that involves using Meteor and React. In my code, I have a class called WebRTC which handles all WebRTC-related logic: class WebRTC { this.isCalling = false; ... } In addition to the WebRTC class, there is ...

JQuery displays 'undefined' on checkbox loaded via Ajax

Currently, I am utilizing a checkbox to activate my select Option tag. The select option tag and checkbox are both loaded via ajax. While the select option works perfectly, the checkbox displays as undefined. However, it functions properly in enabling my d ...

Ways to extract information from a JSON array based on its length and content

Here is an example of some data: { "_id": ObjectId("528ae48e31bac2f78431d0ca"), "altitude": "110", "description": [ { "id": "2", "des": "test" } ], "id": "1", "latitude": "24.9528802429251", ...

Troubleshooting layout problems caused by positioning items at window height with CSS and jQuery

At this moment, my approach involves utilizing jQuery to position specific elements in relation to the window's size. While this method is effective when the window is at its full size, it encounters issues when dealing with a debugger that's ope ...

Tips for avoiding divs from overlapping when the window size is modified

When I maximize the browser, everything aligns perfectly as planned. However, resizing the window causes my divs to overlap. Despite trying several similar posts on this issue without success, I have decided to share my own code. CODE: $(document).read ...