Exploring the power of async/await and promise in TypeScript

I'm puzzled as to why the return type string in this method is showing up as a red error:

exportPageAsText(pageNumber: number): string {
        (async () => {
            const text = await this.pdfViewerService.getPageAsText(pageNumber);
            console.log(text);
            return text;
        })();
}

The error message states:

A function whose declared type is neither 'void' nor 'any' must return a value.
so I tried moving return text; outside of the async block and placing it after })();, but then the text variable became unrecognized.

At that point, I considered changing the method's signature to use a Promise like so:

exportPageAsText(pageNumber: number): Promise<string>

However, I encountered another error stating that

A function whose declared type is neither 'void' nor 'any' must return a value.

If anyone could shed some light on what I might be doing incorrectly, I would greatly appreciate it.

Answer №1

To utilize await, you must have an async function. The code you've written is actually a self-invoking async function, which means that returning a value inside this function won't return it for the main function.

In order to achieve your goal, you need to convert the main function into an async one and define the return type as Promise<string>:

async exportPageAsText(pageNumber: number): Promise<string> {
  const text = await this.pdfViewerService.getPageAsText(pageNumber);
  console.log(text);
  return text;
}

Answer №2

Your current method is waiting for a return before the end, but even the promise declared by async() => {...} is not being returned.

There are two things that need to be changed in your code:

  1. You need to return the async()
  2. You should change the type of return in the method declaration to Promise<string>

In your syntax, it will look like this:

exportPageAsText(pageNumber: number): Promise<string> {
    return (async () => {
        const text = await this.pdfViewerService.getPageAsText(pageNumber);
        console.log(text);
        return text;
    })();
}

Answer №3

Here is my approach using async/await:

    const savePageText = async (pageNum: number): Promise<string> => {
        const pageText: string = await this.pdfViewerService.getPageText(pageNum);
        console.log(pageText);
        return pageText;
    }

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

Utilizing Typescript to inject dependencies and receive arguments within a class

I am currently using InversifyJS with the container. My goal is to inject the templateEngine and provide args (such as host, port, etc...) in the constructor. const container = new Container(); container.bind<MailerInterface>(TYPES.Mailer).to(NodeM ...

Implementing a Beveled Edge on a Shape using ThreeJS

I have put in a lot of effort to find the solution, but unfortunately I have not been successful so far. Currently, I am working on creating a shape using THREE.Shape, and I have the vertices data stored in a file. The shape appears to be straight without ...

Does embedding an Iframe for external files from your server enhance the loading speed of the current page compared to directly loading it on the page?

I'm facing an issue with the loading time of a Facebook post on my webpage index.php. The current method of using the embedded post provided by Facebook is taking too long to load. My solution is to create a separate page, post.php, where only the Fac ...

Encountering an 'Unknown provider' error while running a unit test with AngularJS and Jasmine

I am facing an issue while writing a unit test for a controller in my application. Jasmine is showing an 'Unknown provider' error related to a provider I created for fetching template URLs. This provider is injected into a config function that is ...

Obtain the maximum or minimum value from an associative array using a function and provided parameters

Here is the code I have so far: <!DOCTYPE html> <html> <body> <button onclick="scanarray('a', 'max')">Test with a, max</button> <button onclick="scanarray('b', 'min')">Test with ...

Utilizing JavaScript for loops to extract the final element from an array

I am facing an issue with the second loop within a function that goes through a JSON file. The problem is that it only returns the last item in the array. I need to figure out how to fix this because the chart object should be created on each iteration, ...

Struggling to comprehend the intricacies of these generic declarations, particularly when it comes to Type Argument Lists

I'm currently reviewing the code snippet from the TypeScript definitions of fastify. I am struggling to understand these definitions. Although I am familiar with angle brackets used for generics, most TypeScript tutorials focus on simple types like Ar ...

Currently, I am working on a project and encountering an issue with html2canvas

const handleDownloadImage = async () => { try { const canvas = await html2canvas(cardRef.current); console.log(cardRef.current); const imageData = canvas.toDataURL("image/png"); setImageUrl(imageData); } catch ( ...

Creating 3D Shapes with three.js

I am currently in the process of importing an STL object into my three.js scene. Unfortunately, this particular object seems to be using a large amount of GPU resources for rendering and animation, causing the overall performance of the scene to suffer. B ...

What could be causing my web application to not properly identify angular.js?

As a newcomer to angular, I have been struggling to incorporate it into my web application (VS) as I keep encountering issues with recognizing angular. Despite trying various methods, the result remains the same - angular is not being recognized. I dow ...

Instructions for creating a circular image using the Next.js image component in Next.js version 13

Currently, I'm attempting to replicate an image similar to https://i.sstatic.net/EF5Nd.jpg using the latest version of next.js (version 13) with the next.js image component. However, I am encountering a slight issue where the image appears to be takin ...

JavaScript - Merging the two JSON requests into a unified object

Is there a way to merge two different JSON responses into a single object for easy data manipulation? I've explored various solutions, but none seem to align with my current code structure. Given that I'm new to this, it would be incredibly hel ...

Customize the initial color of the text field in Material UI

I am currently working with the mui TextField component and facing an issue. I am able to change the color when it is focused using the theme, but I cannot find a way to adjust its color (label and border) in its initial state when it's not focused. I ...

Should Redux Reducer deep compare values or should it be done in the Component's ShouldComponentUpdate function?

Within my React Redux application, I have implemented a setInterval() function that continuously calls an action creator this.props.getLatestNews(), which in turn queries a REST API endpoint. Upon receiving the API response (an array of objects), the actio ...

What is the best way to create a TypeScript interface or type definition for my constant variable?

I'm facing challenges in defining an interface or type for my dataset, and encountering some errors. Here is the incorrect interfaces and code that I'm using: interface IVehicle { [key: number]: { model: string, year: number }; } interface IV ...

Express JS causing NodeJS error | "Issue with setting headers: Unable to set headers after they have been sent to the client"

As I embark on my journey to learn the fundamentals of API development, I am following a tutorial on YouTube by Ania Kubow. The tutorial utilizes three JavaScript libraries: ExpressJS, Cheerio, and Axios. While I have been able to grasp the concepts being ...

Is it possible to maintain the input and output types while creating a function chain factory in

Take a look at the following code snippet involving pyramids: /** * @template T, U * @param {T} data * @param {(data: T) => Promise<U>} fn */ function makeNexter(data, fn) { return { data, next: async () => fn(data), }; } retu ...

Attempting to iterate through a Query each loop for the Raphael object

I'm currently facing a challenge with creating a jQuery .each() function to iterate through an array that I've constructed from a Raphael object. While I am able to achieve this using a traditional JavaScript for-loop: for (var i = 0; i < reg ...

Angular 2: A guide to resetting dropdown and text values when changing radio button selections

When the user interface displays two radio buttons - one for YES and one for NO - and the user clicks on YES, a dropdown is shown. Conversely, if the user clicks on NO, a textbox is displayed. How can I clear the values in the dropdown and textbox when s ...

Encountering the error message: "TypeError [ERR_INVALID_ARG_TYPE]: The initial parameter should either be a string, Buffer instance, or Uint8Array."

Having trouble with the payment gateway API and subscription creation. Encountering an error that I can't seem to resolve even after debugging. Despite my best efforts, the error persists. The form and everything else seem to be in order, but the err ...