JavaGeek
JavaGeek

Reputation: 1529

Delay post response in Node JS

I want to do some processing before sending the POST response. But from below code it's sending response without waiting for var processedFile = process(writeToFile); and it's processing the last line response.status(200).json({"file":file_name_output});

Is there anyway to delay the response until the method process(writeToFile); gets completed

app.post('/data', function(request, response){
   // console.log("DATA::"+request.body.data);
    var html_data = request.body.data;
 // Get Random Number
    var random = randomIntFromInterval(1,999);
    //Input Html Location
     writeToFile = directory+random+'-input.html';

    //Output PDF Location
     file_name_output = random+'-output.pdf';
     file_name_output = directory+file_name_output;
     output = directory+random+'-output.pdf';

    // replace the images
    const $ = cheerio.load(html_data);

    $("img").filter(function(i,ele){

     var imageSource = $(ele).attr("src");

    // console.log(" Image["+i+"] Value::"+imageSource);

    if(i==0)
        {
     $(ele).attr("src","hellp.jpg");    
        }
    else
        $(ele).attr("src","home.jpg");  

   });

    //console.log(" Processed html :: "+$.html());


    fs.writeFile(writeToFile, $.html(), function(err) {
        if(err) {
            return console.log(err);
        }

        console.log("The file was saved!");
        var processedFile = process(writeToFile);
        //setTimeout(waitMethod, 3000);
       // var data =fs.readFileSync(processedFile);
       // response.contentType("application/pdf");
        //response.send(data);

        response.status(200).json({"file":file_name_output});

    }); 



}); // data

Upvotes: 0

Views: 158

Answers (1)

Horatiu Jeflea
Horatiu Jeflea

Reputation: 7404

In your case, process is an async function. In order to wait for it, you have to add an async and await:

    fs.writeFile(writeToFile, $.html(), async function(err) {
        if(err) {
            return console.log(err);
        }

        console.log("The file was saved!");
        var processedFile = await process(writeToFile);

        response.status(200).json({"file":file_name_output});
    }); 

Upvotes: 2

Related Questions