简体   繁体   English

web3立即触发回调

[英]web3 instantly firing callback

not sure if I should post this on the Ethereum SE but I have a feeling it is more javascript related, so I'll try here: 不确定我是否应该在以太坊SE上发布此内容,但我感觉它与javascript有关,所以我会在这里尝试:

I have a very simple smart contract that consists of essentially just a getNum function and a setNum function. 我有一个非常简单的智能合约,它基本上只包含一个getNum函数和一个setNum函数。 The smart contract can be viewed here: https://pastebin.com/ci6mbPDq 智能合约可以在这里查看: https//pastebin.com/ci6mbPDq

I am trying to construct a simple frontend to call it. 我正在尝试构建一个简单的前端来调用它。 Essentially, I follow this guide . 基本上,我遵循本指南 A working codepen of my frontend (demonstrating the janky functionality) can be found here: https://codepen.io/heh/pen/PeMmKe As you can see in my codepen, I call my getNum function like: 我可以在这里找到我前端的工作代码(演示janky功能): https ://codepen.io/heh/pen/PeMmKe正如你在我的codepen中看到的,我调用了我的getNum函数:

BasicToken.getNum(0x64319ca297239d8652a0b5f0f12dd6666cb0e05b,

        function(error, result)
        {
            console.log(result.toNumber());
            document.getElementById("target").innerText = result.toNumber();

        }
    );

However, I keep getting "0" as the result. 但是,我一直得到“0”。 On the other hand, my setNum function is able to post a result to the Ropsten blockchain. 另一方面,我的setNum函数能够将结果发布到Ropsten区块链。 However, I notice that both function calls seem to be firing off their callback instantly. 但是,我注意到两个函数调用似乎都立即触发了它们的回调。

Could anyone help me figure out why the function calls return instantly? 任何人都可以帮我弄清楚为什么函数调用立即返回?

Thanks! 谢谢!

The callback is not being called immediately, the problem is you're not sending an actual address, which should be a string, and you're sending a number: 回调没有被立即调用,问题是你没有发送一个实际的地址,这应该是一个字符串,而你发送一个数字:

0x64319ca297239d8652a0b5f0f12dd6666cb0e05b == 5.720054584403591e+47

And you get 0 because that invalid address you're sending doesn't exist in the mapping: 你得到0因为你发送的无效地址在映射中不存在:

mapping (address=>uint) map23;

And if it doesn't exist it will return the default value for uint which is zero. 如果它不存在,它将返回uint的默认值,该值为零。

Send a string and it will work: 发送一个字符串,它将工作:

BasicToken.getNum('0x64319ca297239d8652a0b5f0f12dd6666cb0e05b', () => {})

Furthermore, if you only want the current user to retrieve their own value, and not let other users retrieve that data (They can, since it's public, but not that easy), you should use msg.sender and drop the function parameter. 此外,如果您只希望当前用户检索自己的值,而不让其他用户检索该数据(他们可以,因为它是公开的,但不是那么容易),您应该使用msg.sender并删除函数参数。

function getNum() public view returns (uint) {
   return map23[msg.sender];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM