Home > Enterprise >  Express: response get sent before asynchronous function finishes
Express: response get sent before asynchronous function finishes

Time:09-14


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

     doSomething().then(res.sendFile(path,(err)=>{
        if (err) {
            console.log('err')
          } else {
            console.log('Sent:', fileName)
          }
      }))

async function doSomethig(){

let conf = { url:'', format:'jpeg', out:'./out/test.jpg' }

conf.url = "someurl";

return new Promise(async () => {
  let browser = await puppeteer.launch({
    headless: true,    
    //ignoreDefaultArgs: ['--disable-extensions']
  });
  console.log(`START => Contacting URL: ${conf.url}`)
  const page = await browser.newPage()
  await page.setViewport({ width: 1024, height: 768 })
  await page.goto(conf.url)
  await page.waitForFunction('window.status === "ready"')
  console.log(`DONE => Contacting URL: ${conf.url}`)
  console.log(`START => Screenshot: ${conf.out}`)
  const data = await page.screenshot({
    path: conf.out,
    quality: 100,
    omitBackground: true,
    type: conf.format
  })
  console.log(`DONE => Screenshot: ${conf.out}`)
  //fs.writeFile(conf.out, data,  "binary",function(err) { });
  //console.log(data)
  await browser.close();
})
}

})

doSomething() create a file and save it in a local directory and i want to send it as a response to the get request but the get res.sendfile enters the err branch and prints error be cause the doSomething function don't finish to create the file.

Please help to fix the problem

CodePudding user response:

You're not using the .then() handler correctly: you need to pass a function to it that will be called once the promise has been resolved. Instead, you're executing res.sendFile() immediately.

The correct syntax:

doSomething().then(() => {
  res.sendFile(…);
});

Then in doSomething, you create a new promise for no reason, and with an incorrect syntax.

It should look like this:

async function doSomething() {
  let conf = { url:'', format:'jpeg', out:'./out/test.jpg' };
  conf.url = "someurl";

  let browser = await puppeteer.launch({
    headless: true,    
    //ignoreDefaultArgs: ['--disable-extensions']
  });
  …
  await browser.close();
}
  • Related