D
D
Dymok2020-11-23 20:05:48
JavaScript
Dymok, 2020-11-23 20:05:48

How to give the browser the result of executing an asynchronous function in express.js?

I'm trying to make a site screenshot using express.js
and puppeteer.js

const express = require('express');
const puppeteer = require('puppeteer');

const app = express();
const port = 3000;

app.get('/', (req, res) => {

    //
    res.send('<img src="screenshots/' + getPic() + '">');
});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
});

function makeid(length) {
    var result           = '';
    var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}

async function getPic() {
    const screenName = makeid(5) + '.png';

    const browser = await puppeteer.launch({headless: true});
    const page = await browser.newPage();
    await page.goto('https://ya.ru');
    await page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36');
    await page.setViewport({ width: 375, height: 812 });
    await page.screenshot({path: 'screenshots/' + screenName});
    await browser.close();
    return screenName;
}

But the getPic() function returns [object Promise].
How to correctly place the result of the getPic() function execution in res.send?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Cheremkhin, 2020-11-24
@UnluckySerivelha

app.get('/', (req, res) => {
   getPing().then(data=> res.send('<img src="screenshots/' + data + '">'));
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question