Home > OS >  How to output the value from Promise to http.createServer?
How to output the value from Promise to http.createServer?

Time:02-05

I need to output the value from the getGasPrice() function on the HTTP page. The function is executed asynchronously.

const web3 = createAlchemyWeb3("https://polygon-mainnet.g.alchemy.com/v2/API-KEY");

const http = require('http');

async function getGasPrice() {
    gasPrice = '0';

    await web3.eth.getGasPrice(function (error, price) {
        gasPrice = price;
    });

    return gasPrice;
}

http.createServer((req, res) => {
    

    res.writeHead(200, {'Content-Type': 'text/html'});

    getGasPrice().then((value) => {
        res.write(value);
    })

    res.end();
}).listen(2000, '127.0.0.1');

When I try to output a value to createServer using res.write(value) nothing happens. And when I output the value console.log(value), the value appears in the console. How do I display the value on the site page?

CodePudding user response:

Try this:

http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
    getGasPrice().then((value) => {
        setStatus(value);
        res.write("String(value.code)");
        res.end();
    })
}).listen(2000, '127.0.0.1');

or

http.createServer(async (req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
    let value = await getGasPrice();
    setStatus(value);
    res.write("String(value.code)");
    res.end();
}).listen(2000, '127.0.0.1');
  • Related