Encountering a problem with the JavaScript promise syntax

Using pdfjs to extract pages as images from a PDF file and then making an AJAX call to send and receive data from the server is proving to be challenging. The implementation for iterating through the pages in the PDF was sourced from:

The issue lies in properly structuring the syntax for the promise that triggers the AJAX function only after all required details have been retrieved.

This is the current code snippet:

getDataUrlsAndSizesFromPdf(file).then(proceedAndCheckOnServer(file));

const getDataUrlsAndSizesFromPdf = function(file) {
    PDFJS.disableWorker = true;
    fileReader = new FileReader();
    fileReader.readAsArrayBuffer(file);

    return new Promise(function(resolve, reject) {
        fileReader.onload = function(ev) {   
            PDFJS.getDocument(fileReader.result).then(function (pdf) {
                var pdfDocument = pdf;
                var pagesPromises = [];

                for (var i = 0; i < pdf.pdfInfo.numPages; i++) {
                    var pageNum = i + 1;

                    pagesPromises.push(getImageUrl(pageNum, pdfDocument));
                }

                Promise.all(pagesPromises).then(function () {
                    console.log(pdfPagesInfo);

                    resolve();
                }, function () {
                    console.log('failed');

                    reject();
                });
            }, function (reason) {
                console.error(reason);
            });
        }
    });
}

function getImageUrl() {
    return new Promise(function (resolve, reject) {
        PDFDocumentInstance.getPage(pageNum).then(function (pdfPage) {
            var scale = 1;
            var viewport = pdfPage.getViewport(scale);

            var canvas = document.getElementById('dummy-canvas');
            var context = canvas.getContext('2d');
            canvas.height = viewport.height;
            canvas.width = viewport.width;

            var task = pdfPage.render({canvasContext: context, viewport: viewport})
            task.promise.then(function(){
                var sizesArr = {
                    height : viewport.height,
                    width : viewport.width
                }
                pdfPagesInfo.sizes[pageNum.toString()] = sizesArr
                pdfPagesInfo.images[pageNum.toString()] = canvas.toDataURL('image/jpeg');

                resolve();
            });
        });
    });
}

function proceedAndCheckOnServer() {
    ....
}

The main aim is to ensure that "proceedAndCheckOnServer()" gets executed only after all the necessary details have been fetched from "getImageUrl()". Currently, the execution jumps directly to "proceedAndCheckOnServer()" without waiting for the resolution of the promise from "getDataUrlsAndSizesFromPdf". As I am fairly new to JavaScript promises, any help with proper syntax would be greatly appreciated.

Answer №1

Instead of calling your function directly, consider using a callback function.

When proceedAndCheckOnServer is called, its result is passed as an argument to the then method.

getDataUrlsAndSizesFromPdf(file).then(proceedAndCheckOnServer(file));

Here are a couple of alternatives:

getDataUrlsAndSizesFromPdf(file).then(()=>proceedAndCheckOnServer(file));
getDataUrlsAndSizesFromPdf(file).then(function(){ proceedAndCheckOnServer(file) });

Another option is to resolve your getDataUrlsAndSizesFromPdf promise with file and then use the function without () to chain the result.

getDataUrlsAndSizesFromPdf(file).then(proceedAndCheckOnServer);

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

Tips for updating the content of multiple tabs in a container with just one tab in Bootstrap 4.x

I am attempting to create two tab containers, where one is used to describe the content of a set of files and the other is used as a list of download links for the described files. Initially, I tried controlling the two containers using just one tab. I ca ...

Error: XYZ has already been declared in a higher scope in Typescript setInterval

I've come across an interesting issue where I'm creating a handler function and trying to set the current ref to the state's value plus 1: const useTimer = () => { const [seconds, setSeconds] = useState(0); const counterRef = useRef(n ...

Loading state with suggestions from autocomplete feature on React

In my current project, I have a component that consists of input fields and a button. The button is set to be disabled until the correct values are entered in the input fields. Everything works as expected, but there's an issue with Chrome auto-fillin ...

Is there a method to verify the presence of a message event listener already?

Is there a method to determine if a message event listener is already in place? I am trying to accomplish something similar to this: if(noMessageEventListenerExists) { globalThis.addEventListener('message', async function (data) {}) } I have ...

The image will remain static and will not alternate between hidden and visible states

I am facing a challenge trying to toggle an image between 'hidden' and 'show' My approach is influenced by the post on How to create a hidden <img> in JavaScript? I have implemented two different buttons, one using html and the ...

Parent controller was not in command before Child执行

When working with a parent view and a child view, I encounter an issue with accessing a json file. In the parent view, I retrieve the json file using the following code: $scope.services = Services.query(); factory('Services', function($reso ...

When a new element is added to the DOM, bind a click event to it that will trigger another

When I add an element to the DOM, I bind it with a click function. The problem is that if I add multiple elements and click on any of them, the function triggers multiple times. What causes this behavior and is there a better way to achieve the desired res ...

Efficiently sorting items by category name in PHP with Ajax

Currently, I am working on a functionality that involves two dropdown lists. The first one, located at the top, is for selecting a category of meals. Each option in this dropdown has an associated id_cat value. <option value="1">Pâtis ...

Tips for preserving images while browsing a website built with Angular single-page application

Utilizing Angular's router for component navigation has been beneficial, but I am facing an issue with component reloads when going back. To address the problem of content reloading from the server, I have implemented a solution where the content arra ...

Experiencing issues with the functionality of jQuery AJAX?

I am experiencing difficulties with a jQuery AJAX post. Here is the code: <script> var callback = function(data) { if (data['order_id']) { $.ajax({ type: 'POST', url: '<?php echo $_SERV ...

Unable to properly connect my CSS file to the header partial

I am struggling to include my CSS file in the header partial Here is the link I am using: <link rel="stylesheet" href="stylesheets/app.css"> This is what my directory structure looks like: project models node_modules public stylesh ...

Utilizing jQuery functions within Vue components in Quasar Framework

I've recently started delving into web app development and I'm encountering some basic questions regarding jQuery and Vue that I can't seem to find answers to. I have an application built using the Quasar Framework which frequently involves ...

Tips for swapping out text with a hyperlink using JavaScript

I need to create hyperlinks for certain words in my posts. I found a code snippet that does this: document.body.innerHTML = document.body.innerHTML.replace('Ronaldo', '<a href="www.ronaldo.com">Ronaldo</a>'); Whil ...

Tips for implementing an automatic refresh functionality in Angular

I am dealing with 3 files: model.ts, modal.html, and modal.ts. I want the auto refresh feature to only happen when the modal is open and stop when it is closed. The modal displays continuous information. modal.htlm : <button class="btn btn-success ...

Include a new row in the form that contains textareas using PHP

I'm trying to add a new row to my form, but I'm facing challenges. When I click the add button, nothing happens. If I change the tag to , then I am able to add a row, but it looks messy and doesn't seem correct to me. Here is my JavaScript ...

The largest contentful paint is anticipating an unidentified event

My website is encountering issues with Google Pagespeed and I'm unsure of the cause. The primary bottleneck appears to be the LCP time, which Google reports as taking between 7 and 11 seconds during each test. Upon analyzing the waterfall chart, it ...

Integrating chat functionality with a structured data format

Considering creating a collaborative communication platform, I am contemplating whether to develop a comprehensive application in JavaScript with MVC architecture or utilize it solely for managing message delivery using Node.js and socketIO. Would it be m ...

Is it possible to utilize AngularJS' ng-view and routing alongside jade?

Currently, I am diving into the world of the MEAN stack. I noticed that Express utilizes jade by default, but I decided to experiment with it even though I can easily use html instead. When attempting to route with Angular, like so: ... body div(ng-view ...

Display a custom error message containing a string in an Angular error alert

How can I extract a specific string from an error message? I'm trying to retrieve the phrase "Bad Request" from this particular error message "400 - Bad Request URL: put: Message: Http failure response for : 400 Bad Request Details: "Bad Request ...

Error: JSON at position 1 is throwing off the syntax in EXPRESS due to an unexpected token "

I'm currently utilizing a REST web service within Express and I am looking to retrieve an object that includes the specified hours. var express = require('express'); var router = express.Router(); /* GET home page. ...