chi*_*ro2 4 javascript node.js express ethereum web3js
我希望有一个网站可以通过私有以太坊区块链实时更新用户的财富。
当前解决方案(已损坏)
我打开了一个到正在挖矿的私有以太坊区块链的 websocket,我想在前端更新我的 Coinbase 余额。我的代码如下:
const express = require("express");
const Web3 = require("web3");
var app = express();
app.get("/", (req, res) => res.send("hello world from ping ether application"));
app.get("/ping-ether", function(req, res){
var web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
var event_newBlockHeaders = web3.eth.subscribe("newBlockHeaders", function(err, result){
if (err){
console.log(err)
} else {
let acctPromise = web3.eth.getAccounts().then(function(accts){
let balance = web3.eth.getBalance(accts[0]).then(function(bal){
console.log("user: ", accts[0]);
console.log("balance: ", bal);
res.end("new balance for user: " + bal)
});
});
}
});
});
// run the server
app.listen(3000, () => console.log("web app listening on port 3000"));
Run Code Online (Sandbox Code Playgroud)
显然,这并没有在前端实时更新,即使最内部的回调不断触发,正如我可以在控制台上确认的那样。我想要三件事:
我应该如何更改此代码,以便前端具有 coinbase 余额的实时行情
一般来说,代码的嵌套承诺让人感觉很糟糕。如何重构它,以便每次导航时不必建立 websocket 连接/ping-ether?
未经测试,但类似这样的东西应该可以工作:
const express = require("express");
const Web3 = require("web3");
var app = express();
var web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
var balance = -1;
web3.eth.getAccounts().then(accounts => {
return web3.eth.subscribe("newBlockHeaders", (err, result) => {
if (err) {
console.log(err);
} else {
web3.eth.getBalance(accounts[0]).then(bal => {
console.log("user: ", accounts[0]);
console.log("balance: ", bal);
balance = bal;
});
}
})
}).then(() => {
app.listen(3000, () => console.log("web app listening on port 3000"));
});
app.get("/", (req, res) => res.send("hello world from ping ether application"));
app.get("/ping-ether", function (req, res) {
res.end("new balance for user: " + balance);
});
Run Code Online (Sandbox Code Playgroud)
主要思想是设置一次 Websocket 连接和订阅,然后仅使用当前余额响应传入的 Web 请求。我还尝试通过返回订阅承诺来清理嵌套的承诺。
| 归档时间: |
|
| 查看次数: |
3467 次 |
| 最近记录: |