Using web3js 0.20.2 and truffle-contract, I have been getting public properties of my contract by doing

Foo.deployed().then(function(instance) { 
    instance.rate.call().then((r) => {
        console.log(r)
    })
});

Came across a less verbose way of writing the same code [here], which does something like

Foo.deployed().then(function(instance) { 
    console.log(instance.rate())
});

In the linked webpage, the author suggested the following where k is the contract instance:

for(i = 0; i < k.size(); i++) {
    someFunc( k.balances(k.addressLUT(i)) );
}

to avoid

for(i = 0; i < k.size(); i++) {
    k.addressLUT(i).call().then((res) => {
        k.balances(res).call().then((res) => {
            someFunc(res)
        })
    })
}

However when I try out the second method, why is instance.name() giving me a promise, similar to using instance.name.call()? Shouldnt we get the value immediately without waiting for the Promise to be resolved?

instance.rate()

> instance.rate()

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: BigNumber

instance.rate.call()

> instance.rate.call()

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: BigNumber
up vote 1 down vote accepted

truffle-contract treats constant method calls as promises to be consistent in it's library API design with transactional method calls. The best wait to simulate synchronous calls is to use async/await when dealing with JavaScript promises.

Here's an example:

async function example () {
    const k = await Foo.deployed()

    for (let i = 0; i < k.size(); i++) {
        someFunc(await k.balances(await k.addressLUT(i).call()))
    }
}

If your solidity method is using the constant modifier than you don't need to use .call() in your JavaScript. You should always use constant if your function doesn't modify any storage state because it tells the compiler that it'll only perform read actions therefore it infers no gas costs.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.