Amber Johnson
Amber Johnson

Reputation: 65

.then() function never running for call to blockchain

Please find below my code snippet. Here credentialHash is not being set in the .then() call. Neither the "In then" or "Callback rejected" are being printed so I know that it is not running but I cant understand why. I've also included code for the setHash function in my smart contract.

let hash;
    await ipfs.add(JSON.stringify(this.state.credential)).then((result, error) => {
      hash = result.path;
      if (error) {
        console.error(error)
        return;
      }
      // Store hash on blockchain
      console.log("Hash before BC:" + hash);
      this.state.contract.methods.setHash(hash).send({from: this.state.account}).then((resolve) => {
    console.log("In then")
    this.setState({credentialHash: hash});
  }, (rejected) => {
    console.log("Callback rejected");
  });
      console.log("After setting:" + this.state.credentialHash);
    });

function setHash(string memory _CredentialHash) public returns(string memory) { credentialHash = _CredentialHash; return _CredentialHash; }

The result returned from console.log(this.state.contract.methods.setHash(hash).send({from: this.state.account})) is :

Proxy {promise: Promise, eventEmitter: EventEmitter, resolve: ƒ, reject: ƒ}
[[Handler]]: Object
get: ƒ proxyHandler(target, name)
[[Prototype]]: Object
[[Target]]: PromiEvent
eventEmitter: EventEmitter
_events: Events
[[Prototype]]: Object
_eventsCount: 0
[[Prototype]]: Object
promise: Promise
[[Prototype]]: Promise
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined
reject: ƒ ()
resolve: ƒ ()
[[Prototype]]: Object
[[IsRevoked]]: false

Upvotes: 0

Views: 178

Answers (2)

Amber Johnson
Amber Johnson

Reputation: 65

The default number of transactionConfirmationBlocks is 24 which takes a long time to complete. Setting this to 1 as below solved my issue.

this.setState({contract: new web3.eth.Contract(
      credentialArtifact.abi,
      deployedNetworkCred.address,
        {transactionConfirmationBlocks: 1}
  )});

Upvotes: 0

Jeremy Thille
Jeremy Thille

Reputation: 26400

Try dropping the .then() syntax entirely and use only the async/await style. What does the code below give?

let hash, result;

try {
  result = await ipfs.add(JSON.stringify(this.state.credential))
  hash = result.path;
} catch (error) {
  console.error(error)
  return;
}

// Store hash on blockchain
console.log("Hash before BC:" + hash);

try {
  await this.state.contract.methods.setHash(hash).send({
    from: this.state.account
  })
} catch(error) {
  console.log("Callback rejected");
  return
}

this.setState({
  credentialHash: hash
});

console.log("After setting:" + this.state.credentialHash);

Upvotes: 1

Related Questions