[英]I want to use a promise return value inside the get method. nodejs rest api
I am creating a rest api.我正在创建一个休息 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.
我的 get 方法会根据合约的总供应价值返回结果,否则它不会响应,但我对合约的请求会返回一个 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)
}
});
});
Try saving the promise whose value will end up being the total value尝试保存价值最终成为总价值的承诺
const pTotalSupply = NameContract.methods.totalSupply().call();
(assuming this is valid - the .call
method looks a little strange). (假设这是有效的 -
.call
方法看起来有点奇怪)。 Options then are to然后选项是
pTotalSupply
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,pTotalSupply
之前不要启动服务器,前提是总供应量是一个静态值并且服务器必须处理一个名称合同,app.get
handler, either by using an await
operator inside an asynchronous function body, or wrapping request processing in a promise then
argument function, orapp.get
处理程序中获得结果,或者通过在异步函数体内使用await
运算符,或者将请求处理包装在 promise then
参数函数中,或者then
call to save the supply value and call next
in a two part app.get
handler.then
调用以保存供应值并在两部分app.get
处理程序中调用next
。 This is more an express oriented solution using a pattern along the lines of:app.get('/:id', (req, res, next) => {
pTotalSupply.then( value => {
res.locals.value = value;
next();
}
.catch( err => res.status(500).send("server error")); // or whatever
}
, (req, res) => {
const value = res.locals.value;
let id = parseInt(req.params.id);
// process request with value and id:
...
});
The second option is covered in answers to How to return the response from an asynchronous call第二个选项包含在如何从异步调用返回响应的答案中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.