Sending a response with Express before an asynchronous function has completed


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

Answer №1

Your usage of the .then() handler is incorrect: you must provide a function that will be executed after the promise is resolved, instead of calling res.sendFile() immediately.

The proper syntax is:

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

Furthermore, in the doSomething function, you are unnecessarily creating a new promise with incorrect syntax.

A correct implementation should resemble the following:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The ng-repeat directive in AngularJS does not function properly when making a service call over HTTP

I am working with a single array item that contains complex JSON objects, and I am tasked with accessing these objects using ng-repeat in AngularJS. I have created a fiddle for reference. If anyone has any solutions, I am open to suggestions. The specifi ...

calculating the total amount of continuous occurrences

I am trying to group consecutive repetitions of elements in a list. Here is the list: list = ['green','green','red','blue','red','blue','yellow','white','black',&apos ...

How can I retrieve the value from the input field using vue.js?

I am currently utilizing the vue-js-toggle-button library. While I understand that I can access the value inside the name using $refs, the issue arises as I have 3 toggle buttons and cannot set a Ref because I want to retrieve the name value dynamically i ...

Retrieve the chosen language while utilizing the $translate feature

I have successfully integrated the $translate project from this source into my AngularJS application. While I have configured the default language in my app.config() using $translateProvider, I am now wondering how to retrieve the selected language within ...

Having issues with inline conditional statements in Angular 5

There is a minor issue that I've been struggling to understand... so In my code, I have an inline if statement like this: <button *ngIf="item?.fields?.assetType !== 'tool' || item?.fields?.assetType !== 'questions'">NEXT< ...

Talebook: Unable to modify UI theming color

As I embark on creating my own theme in Storybook, I am closely following the guidelines outlined here: Currently, I have copied the necessary files from the website and everything seems to be working fine. However, I am facing an issue when trying to cus ...

Can PHP be incorporated with vBulletin seamlessly?

I am looking to seamlessly integrate vBulletin into a PHP page. I don't want to create a skin that simply matches the site's appearance, but rather have the forum fully integrated with the site. Of course, the skin would need to be modified to ma ...

What should we do to resolve the uncommon use of the 'this' es-lint error? Which rule should we disable?

Recently, I encountered an issue with my Nuxt setup that is configured with el-lint and prettier. Every time I try to use 'this' within my template, it throws up an error unexpectedly. 6:15 error Unexpected usage of 'this' vue/this ...

The path is visible, yet the ajax call does not make it through - it's simply "off course"

rake routes is used to verify the existence of a route: control1_route1 DELETE /control1/route1(.:format) However, when attempting to make a "delete" request to this route: var url = "<%= control1_route1_url %>"; $.ajax({url: url, type: "D ...

Exploring the functionality of the 'useBodyParser' option in Nestjs

Issue with 'useBodyParser' in Nestjs Application I am encountering an error when trying to utilize the useBodyParser option on my Nestjs application instance. Error: Property 'useBodyParser' is not found on type 'NestExpressAppl ...

Mapping technologies provided by Google Maps Geocoding API are top-notch

I'm having an issue with the code below. It should display a map and a div section, but for some reason, it's not showing the marker point on the map. Can anyone provide assistance? Thank you in advance! <!DOCTYPE html> <html> <he ...

Stop the npm start command with a specific error message if the file is not found in the repository

Can the npm start process be stopped or cancelled if a specific file is not found in your codebase? I am looking to end the process if the file dev-variables.js is missing, preferably displaying a custom error message like "You are missing the dev-variabl ...

Adjust the size of an element in response to changes in the size of

I've implemented a jQuery function to resize an element dynamically based on window size changes: $(window).resize(function() { topHeight = $("#top").height(); height = $(window).height() - 210; $("#container").height(height); $("#g").height( ...

LinkButton with an href value is attached to a table and triggers an onclick event

I am currently working on making the buttons in our web application more user-friendly for international users. I have successfully used a sprite image and applied CSS classes to create these buttons. The structure of the buttons is set up as follows: &l ...

What is the process for testing an expressApp.post() function?

Currently, I am a C# developer diving into the world of node.js and Dialogflow. My goal is to develop a webhook in node.js on Azure to serve as a fulfillment for my Dialogflow project. My understanding is that I need to modify the following: exports.dial ...

Is there a syntax error in Javascript when using a string and variable with the GET method?

Is there a way to send a value using the get method? In JavaScript, we need to use the + symbol to concatenate strings. But my issue goes beyond this simple problem. If I attempt the following: Let's say; var sID = 16; var rID = 17; EDIT-2: I act ...

Issues arising when sending an empty object via Post request in NodeJs/Express?

Having trouble with a POST request - trying to post a JS object, but the values from the input fields are not being included, resulting in an empty object being posted. Can't seem to identify the error! app.js function addPoem() { event.preventDefa ...

Encountering difficulties loading .mtl and .obj files using react-three-renderer

I'm currently utilizing react-three-renderer to load .obj and .mtl files, but I'm encountering difficulties in rendering the model. Instead, a cube is being rendered inside the div. My goal is to replace the cube with my desired .obj model. Inst ...

Converting human-readable dates into a Date object

How can I reliably convert human-entered dates into a Date() object for my project that utilizes a ML text extractor? Although seemingly straightforward, the issue lies in the wide variety of formats used by individuals when entering dates, ranging from " ...

The Vue.js 2 router is exclusively pulling components from the navigation bar, rather than directly from the URL

After selecting a page from the menu, the correct component loads. However, directly accessing the page URL does not display the content. This is the main template (which contains the menu): <template> <div class="row"> <div cl ...