-1

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

});
TylerH
  • 20,799
  • 66
  • 75
  • 101
mert
  • 1
  • 1
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – esqew Feb 28 '22 at 23:17
  • what do the two first lines of code have to do with the API? the value is available here `(value => console.log(value))` so, do what you want with it in that `.then` block ... currently those lines have nothing to do with the `get /:id` endpoint ... so why have you included two unrelated bits of code - you say your trying, but without showing code that is meaningful nobody can help – Bravo Mar 01 '22 at 00:15

1 Answers1

0

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

traktor
  • 17,588
  • 4
  • 32
  • 53