I have followed following solution.
When I try to do shh.getPrivateKey(kId).then(console.log)
I have received following error, please note that this line works under web3.py
:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Returned error: invalid argument 0: json: cannot unmarshal object into Go value of type string
[Q] How could I fix this error?
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); if(!web3.isConnected()){console.log("notconnected"); process.exit();} var Shh = require('web3-shh'); // "Shh.providers.givenProvider" will be set if in an Ethereum supported browser. var shh = new Shh(Shh.givenProvider || 'http://localhost:8545'); var kId = shh.newKeyPair().then(console.log); //b9180e43e5b712868482173d71cf18ff78900e645699d00f9129d6458aaa1fb7 var privateKey = shh.getPrivateKey(kId); //Error Occurs!!!
Best Answer
You need to use callbacks so that the asynchronous functions return a value when it has finished processing. Or use async / await.
The line
var privateKey = shh.getPrivateKey(kId);
will get executed before kId has a value, because the newKeyPair function has not completed yet.https://web3js.readthedocs.io/en/1.0/callbacks-promises-events.html
Callbacks documentation, examples: http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/
So using async / await instead of callbacks, you can try something like: