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

The powers of jQuery and CSS selectors

Previously, I utilized the following code to extract text from the data-placeholder attribute and apply it as a placeholder for my div. [contentEditable=true]:empty:not(:focus):before { content:attr(data-placeholder) } While this method worked well b ...

Utilizing unique symbols to dynamically add form elements to an HTML page with jQuery's append method

I am facing an issue with creating forms on my HTML page. Here is an example of how I am trying to do it: <form action="/tasks/<%= allTasks.e[0].id %>/delete" method="POST"> <button class="deleteTask">Delete</button> </f ...

Using jQuery, you can easily apply a new class to a div when it is

I'm currently facing an issue with adding a class of "active" to a div upon clicking it using jQuery. My goal is to apply the css class of active in order to give the button a distinct color (or the hover effect.) Unfortunately, I have been unsuccess ...

Summernote - When validating text, it is shown as raw HTML

I have integrated Codeigniter with Summernote on the frontend. In a form, if certain fields are left empty, the same page reloads for validation checking. The JavaScript and CodeIgniter code I am using is as follows: $(window).load(function(){ &l ...

Inconsistencies in Height Among JQuery Elements

I am encountering an issue with my datatable.js, where I am attempting to limit its height based on a specific row number, such as 4.5 rows. However, I am facing a problem with the row height (tr height). For example, when using the following method with m ...

Can anyone help with displaying a PNG image in Vue/Node/Express? I am struggling to show the image that I sent from a Node.js server to a Vue app client

In my Node/Express application, I've set up a route like this: app.get('/get-image', function(req, res) { ... res.sendFile(path.join(__dirname, '..', account.profileImg)); }) Now in my client-side Vue app, I'm tryi ...

Redirect to a specific webpage depending on a certain condition

I currently have a home page set up and now I would like to create a homePlus page that is controlled by a localStorage variable called alreadyShown. The concept is that once the homePlus page is shown for the first time, we will change the value of alread ...

How can you provide arguments to a mock function?

While using jest for unit testing, I am encountering the following line of code: jest.mock('../../requestBuilder'); In my project folder, there is a __mocks__ subfolder where I have stored my mock requestBuilder.js file. The jest unit test i ...

Employing an unchanging Map format for observation

I'm currently working on implementing a synchronization mechanism using observable and Map structures from Immutable.js. However, I'm encountering an issue where the Map is unable to function as an observable or perhaps I might be approaching it ...

Uploading images using the Drag and Drop feature in HTML

Hello, I'm having an issue with the drag and drop functionality. I want to expand the size of the input to cover the entire parent div, but for some reason, the input is appearing below the drag and drop div. Can anyone assist me with this? https://i. ...

Encountering an async issue with npm exiftool in JavaScript

I'm facing issues with npm exiftool usage. (https://www.npmjs.com/package/exiftool) I'm attempting to perform some tasks using it. Iterate through image files in a specific folder Retrieve 'xpKeywords' data of each image file Write th ...

Expanding rows in Angular UI-Grid: Enhancing user experience with hover functionality

Struggling to add a hover effect to the rows in an Angular UI grid. The goal is for the entire row to change background color when hovered over, but with an expandable grid that includes a row header, applying CSS rules only affects either the row header o ...

Bring in a 3-dimensional model using JSONLoader in three.js

I'm facing some challenges with incorporating a simple 3D object created in Maya into my Three.js project using JSONLoader. The object consists of various materials (Lambert and Phong) and different colors. I used Maya to create a .obj file, then Ble ...

Tips for refreshing the page upon Geolocation request

I am working on a HTML5 project that requests geolocation from the user. Here is an image of what it looks like: My main query is: Is there a way to refresh the page automatically once the user grants permission to share their location? Are there any Jav ...

Keeping an Rxjs observable alive despite encountering errors by simply ignoring them

I am passing some values to an rxjs pipe and then subscribing to them. If there are any errors, I want to skip them and proceed with the remaining inputs. of('foo', 'bar', 'error', 'bazz', 'nar', 'erro ...

Having trouble clearing the interval after setting it?

I developed a slideshow script called function slide(). The intention is for this function to begin when the 'play' button is clicked and pause when the 'pause' button is clicked. I implemented setinterval and it functions properly, how ...

Ways to time animations differently and activate two animations at the same time in every loop

I have 3 hidden text boxes that I want to fade in and slide down simultaneously by 40px when the DOM loads. They should be staggered so that each one triggers after the previous animation finishes. Below is the relevant JavaScript code snippet: jQuery(fu ...

Issues with Node JS app's handling of php mailer code

I've made a basic website using the Node JS framework and included a php mailer for handling the contact form. Unfortunately, I'm facing issues getting it to function properly. Could it be possible that there is an underlying problem with Node JS ...

Creating a window.variable in a jQuery ajax callback using CoffeeScript

This particular project is built using rails and backbone-on-rails framework. Despite my efforts, I have been facing an issue with setting a global variable in a response callback function. Here's what I have attempted so far: 1) Initialization of t ...

Is it possible to link a JavaScript object to a dropdown Select Option?

As I work on populating a select list with options using Javascript, I am looking for a way to attach a corresponding Javascript object to each option that can be easily accessed during the change event. While formulating this question, I began thinking a ...