我想在 get 方法中使用 Promise 返回值。 Node.js 休息 API
我正在创建一个休息 api。我的 get 方法将根据合约的总供应值返回结果,否则不会响应,但我对合约发出的请求返回一个承诺。我该如何使用这个值?
const NameContract = new web3.eth.Contract(abi, '0xE3A2beCa..........1D901F8');
NameContract.methods.totalSupply().call().then(value => console.log(value))
app.get('/:id', (req, res) => {
let id = parseInt(req.params.id);
//I want to use an if here.
//I want to throw the query according to the value returned from above,
// but it returns a promise, how can I use it value?
nft.findOne({ id: id }, (err, doc) => {
if (doc != null) {
res.json(doc)
}
else {
res.status(404).json(err)
}
});
});
I am creating a rest api. My get method will return the result according to the total supply value of the contract or it will not respond, but the request I made to the contract returns a promise. How can I use this value?
const NameContract = new web3.eth.Contract(abi, '0xE3A2beCa..........1D901F8');
NameContract.methods.totalSupply().call().then(value => console.log(value))
app.get('/:id', (req, res) => {
let id = parseInt(req.params.id);
//I want to use an if here.
//I want to throw the query according to the value returned from above,
// but it returns a promise, how can I use it value?
nft.findOne({ id: id }, (err, doc) => {
if (doc != null) {
res.json(doc)
}
else {
res.status(404).json(err)
}
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试保存其值最终将成为总值的承诺
(假设这是有效的 -
.call
方法看起来有点奇怪)。然后,选项是pTotalSupply
之前不启动服务器,提供总供应量是一个静态值,并且服务器必须处理一个名称合同,app.get
处理程序中获取结果,方法是在异步函数体内使用await
运算符,或者将请求处理包装在 Promise>then
参数函数,或then
调用来保存供应值并在两部分app.get
处理程序中调用next
。这更像是一种面向表达的解决方案,使用以下模式:第二个选项包含在 如何从异步调用返回响应
Try saving the promise whose value will end up being the total value
(assuming this is valid - the
.call
method looks a little strange). Options then are topTotalSupply
above has been fulfilled, provided total supply is a static value and there to be only one name contract the server has to deal with,app.get
handler, either by using anawait
operator inside an asynchronous function body, or wrapping request processing in a promisethen
argument function, orthen
call to save the supply value and callnext
in a two partapp.get
handler. This is more an express oriented solution using a pattern along the lines of:The second option is covered in answers to How to return the response from an asynchronous call