What is the most effective method for delivering a Promise after an asynchronous request?

Currently, I am working on creating an asynchronous function in TypeScript that utilizes axios to make an HTTP request and then returns a Promise for the requested data.

export async function loadSingleArweaveAbstraction(absId : string) : Promise<AbstractionPreview> {

    let abstractionPreview : AbstractionPreview = await axios({
        method: 'get',
        url: ARWEAVE_URL + absId,
        responseType: 'json'

    }).then(function(response) {
        return {
            name: response.data.name,
            imageUri: response.data.image,
            symbol: response.data.symbol,
        };
    }).catch(function(v) {
        return { name: "Null", imageUri: "null", symbol: "null" };
    });

    return abstractionPreview;
}

I am questioning whether this is the most efficient way to handle the response from the asynchronous call. Is it necessary to use await or could I eliminate it and return directly within the then and catch blocks? Additionally, relying on the catch block to return a dummy AbstractionPreview seems somewhat clumsy.

Answer №1

It is generally advised to avoid mixing await and .then() in the same function. Instead, it's recommended to choose one style over the other for a particular function. Although the code you provided will function correctly, here are two more consistent ways to write it:

Here is an example without using async/await:

export function loadSingleArweaveAbstraction(absId : string) : Promise<AbstractionPreview> {

    return axios({
        method: 'get',
        url: ARWEAVE_URL + absId,
        responseType: 'json'

    }).then(function(response) {
        return {
            name: response.data.name,
            imageUri: response.data.image,
            symbol: response.data.symbol,
        };
    }).catch(function(e) {
        console.log(e);
        return { name: "Null", imageUri: "null", symbol: "null" };
    });
}

And here is an example using async/await:

export async function loadSingleArweaveAbstraction(absId: string): Promise <AbstractionPreview> {
    try {
        let response: AbstractionPreview = await axios({
            method: 'get',
            url: ARWEAVE_URL + absId,
            responseType: 'json'

        });
        return {
            name: response.data.name,
            imageUri: response.data.image,
            symbol: response.data.symbol,
        };
    } catch (e) {
        console.log(e);
        return { name: "Null", imageUri: "null", symbol: "null" };
    }
}

There isn't necessarily a "right" way between these two options. It ultimately depends on personal preference. I personally find await easier to read when dealing with multiple asynchronous operations that need to be sequenced, as opposed to chained .then() handlers. When there is only one asynchronous operation, both methods can be equally simple.

It's important to always log errors that may occur. Failing to do so could lead to issues within your system, where errors are hidden and difficult to detect.

P.S. If there are any TypeScript syntax errors present, please feel free to correct them as I am not well-versed in TypeScript.

In both cases, we are essentially waiting for the asynchronous call to complete before returning. What then is the purpose of making asynchronous calls if they seem to behave synchronously?

Even though these functions appear to operate synchronously due to the use of await, they actually return a promise immediately when the asynchronous axios() call is initiated. This allows the caller to execute other tasks while awaiting the completion of these operations. Once the asynchronous task finishes, the functions process the results and resolve the initial promise, notifying the caller of the final outcome. Therefore, this is non-blocking and asynchronous behavior, allowing Nodejs and the caller to handle other events concurrently.

Can an unfulfilled promise be returned?

Yes, both examples already return an unfulfilled promise, which is typically the case when working with promises.

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

Develop a series of sequential tests for the playwright to execute

Can someone assist me with my code? I am attempting to write a test in Playwright that navigates to the forgot password page, creates a new password, and then tries to log in using that new password. However, I am encountering an issue with retrieving the ...

The TypeScript Promise error codes TS2304 and TS2529 are causing confusion among

I came across the code below: function asyncTask(): Promise<string> { return new Promise<string>(resolve => resolve); } This code resulted in the following error: TS2304: cannot find name 'Promise' To address this issue, ...

Verify enum values within controller function

I am dealing with a query parameter in my REST API that should be restricted to specific values according to an enum type. I need to find a way to handle a "Bad Request" error if the client provides any value outside of this enum. Here is what my enum loo ...

Ways to access configuration settings from a config.ts file during program execution

The contents of my config.ts file are shown below: import someConfig from './someConfigModel'; const config = { token: process.env.API_TOKEN, projectId: 'sample', buildId: process.env.BUILD_ID, }; export default config as someCo ...

Saving a group of selected checkboxes as an array in Ionic: a step-by-step guide

I am working on a simple form with checkboxes and I need to send only the checked boxes to TypeScript. However, when I attempt to save the data by clicking the save button, I encounter an error message {test: undefined} Below is the form layout: <ion-c ...

Tips for efficiently constructing a Docker container using nodejs and TypeScript

Struggling for the past couple of days to get the project running in production, but it keeps throwing different errors. The most recent one (hopefully the last!) is: > rimraf dist && tsc -p tsconfig.build.json tsc-watch/test/fixtures/failing.t ...

Passing data from getServerSideProps to an external component in Next.js using typescript

In my Index.js page, I am using serverSideProps to fetch consumptions data from a mock JSON file and pass it to a component that utilizes DataGrid to display and allow users to modify the values. export const getServerSideProps: GetServerSideProps = async ...

The data structure '{ recipe: null; }' cannot be matched with type 'IntrinsicAttributes & Recipe'

Currently, I am working on an app that integrates ChatGPT to fetch recipes based on user-input ingredients. After receiving the JSON response from CGPT, I aim to display a Recipe "Card" component. However, I encounter an error titled above when attempting ...

Error: The first certificate could not be verified, although I included rejectUnauthorized: false option

I have encountered an issue with my getServerSideProps() function, as it is throwing an error when trying to call an external API: FetchError: request to https://nginx/api/items failed, reason: unable to verify the first certificate The self-signed cert ...

How can I transfer an instance of a class to dataTransfer.setData?

So I created a new instance of a class: let item = new Item(); Next, I attempted to serialize the item and add it to dataTransfer for drag and drop functionality: ev.dataTransfer.setData("info", JSON.stringify(item)); At some point, I need to retriev ...

Testing for expressjs 4 using Mocha revealed unexpected behavior when attempting to spy on a function called within a promise. Despite setting up the

I have encountered a situation with some test cases structured like this: it('does stuff', function(done) { somePromise.then(function () { expect(someSpy).to.have.been.called done() }) }) When the assertion in a test case fails, it ...

Ways to reveal heavily nested components when the Angular change detector fails to detect them

A particular component called Grid has been implemented with the following template: <div *ngFor="let row of item.rows"> <div *ngFor="let col of row.cols"> <div *ngFor="let grid of col.items"> < ...

Utilizing ngModel with an uninitialized object

What is the most effective way to populate an empty instance of a class with values? For example, I have a User Class and need to create a new user. In my component, I initialize an empty User Object "user: User;". The constructor sets some properties, w ...

What is the best way to exempt a unique situation from a directive's operation?

While troubleshooting a bug related to search functionality on my page, I encountered an issue with the search component. The search feature is working correctly and returning the expected values. However, when I clear the search criteria, I noticed that t ...

Issue with TypeScript Functions and Virtual Mongoose Schema in Next.js version 13.5

I originally created a Model called user.js with the following code: import mongoose from "mongoose"; import crypto from "crypto"; const { ObjectId } = mongoose.Schema; const userSchema = new mongoose.Schema( { //Basic Data ...

Angular D3 - The method 'getBoundingClientRect' is not present in the 'Window' type

Check out this StackBlitz demo I created: https://stackblitz.com/edit/ng-tootltip-ocdngb?file=src/app/bar-chart.ts In my Angular app, I have integrated a D3 chart. The bars on the chart display tooltips when hovered over. However, on smaller screens, th ...

Avoid invoking a TypeScript class like a regular function - _classCallCheck prevention

I am currently developing a TypeScript library that needs to be compatible with all versions of JavaScript. I have noticed that when calling a class in TS without using new, it does not compile properly, which is expected. In ES6/Babel, a class automatica ...

Executing TypeScript Mocha test cases using ES6 modules

Setting up mocha tests for the TypeScript App in my Rails application has been a bit of a challenge. Initially, I added a basic test to kick things off, but encountered the following error: /home/bernhard/Programs/ruby/cube_trainer/jstests/utils/optional. ...

How can I transfer data to a different component in Angular 11 that is not directly related?

Within the home component, there is a line that reads ...<app-root [message]="hii"> which opens the app-root component. The app-root component has an @input and {{message}} in the HTML is functioning properly. However, instead of opening t ...

Is there a method or alternative solution for deconstructing TypeScript types/interfaces?

Imagine a scenario where a class has multiple type parameters: class BaseClass<T extends T1, U extends U1, V extends V1, /* etc. */ > Is there a method to consolidate these type arguments in a way that allows for "spreading" or "destructuring," sim ...