'I want to use a promise return value inside the get method. nodejs rest api

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)
        }
    });

});


Solution 1:[1]

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). Options then are to

  • Not start the server until 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,
  • Wait for the result to be obtained within the app.get handler, either by using an await operator inside an asynchronous function body, or wrapping request processing in a promise then argument function, or
  • Using a promise then call to save the supply value and call next in a two part app.get handler. 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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 traktor