Waiting for two promises in feathersJS

// users.hooks.js

const userDeletion = require('../userdeletion/userDeletion');
const triggerUserDeletion = () => {
  return async (context) => {
    const userDeletionRes = userDeletion(context);
    const userDeletionResRes = userDeletionRes(context);
    await Promise.all(
      [userDeletionResRes]
    );
  };
};

// userDeletion.js

module.exports = () => {

  return async (context) => {

    const userDeletionResult = await context.app.service('replicate').remove(
      {
        // ...
      }
    );

    const userDeletionResultData = userDeletionResult.data[0];
    console.log(userDeletionResultData);

  };
};

Here is my custom hook implementation. How can I properly wait for the response of 2 separate services instead of just one?

Answer №1

To optimize your code, it is recommended that you create individual promise objects for each asynchronous task, and then use either

await Promise.all(promise1, promise2)
or
await Promise.allSettled(promise1, promise2)
to effectively pause execution until both promises have resolved.

By avoiding calling await on each promise separately, you can allow multiple requests to run concurrently, thereby improving the efficiency of the function that relies on their data. This advantage becomes more apparent as the number of requests increases, with even just two requests resulting in a significant reduction in wait time.

await Promise.all() will wait for all promises to resolve, but will immediately throw an error if any of them reject. This feature proves beneficial when both requests must succeed for the program to continue executing, facilitating prompt error handling.

await Promise.allSettled() will await the resolution or rejection of all promises before enabling you to iterate over the returned list of objects and assess their status field to determine success or failure. This approach is particularly useful when you require detailed error management or can gracefully recover from failed requests to proceed with the function's operation smoothly.

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 onClick event handler is functioning properly, but the ngOnInit() lifecycle method is not executing the function as

I have created a filter function that is applied to elements in a list. It works when I use it on the page with a click event, like this: <button (click)="FilterFn5()"> do </button> However, it does not work when I put the function i ...

Building a Dynamic Checkbox Validation Feature in Angular Using Data retrieved from an API

Currently, I have a function that retrieves and displays a list obtained from an API: displayEventTicketDetails() { this.Service .getEventTicketDetails().subscribe((data: any) => { this.eventTicketDetails = data.map(ticket => ticket. ...

Troubleshooting CKEditor5 installation: Dealing with the error 'Property 'create' is undefined'

I am in the process of implementing CKEditor5 on my website using the npm package @ckeditor/ckeditor5-build-classic. I have installed version 12.0.0, which is the most recent update available. Following the setup method outlined at this link, it seems lik ...

collaborating on data within closely related components in a table display

I am trying to figure out the best way to pass data among sibling components. For example, let's say I have a data entry grid structured like this: <tr *ngFor="let item of frm.controls.items.controls; let i=index" [formGroupName]="i"> <td ...

Automate your Excel tasks with Office Scripts: Calculate the total of values in a column depending on the criteria in another column

As a newcomer to TypeScript, I have set a goal for today - to calculate the total sum of cell values in one column of an Excel file based on values from another column. In my Excel spreadsheet, the calendar weeks are listed in column U and their correspon ...

Typescript: Mastering the Art of Uniting Diverse Types

I'm in the process of developing a React application using Typescript. One of my components is responsible for fetching user data from the server (I'm using firebase), and then storing this data in the component's state. // Defining a cus ...

What could be causing the FormArray value to not update when I make changes to an input field?

My Angular reactive form includes several FormControl elements and one FormArray element. competitionForm!: FormGroup; this.competitionForm = new FormGroup({ name: new FormControl(this.competition.name, []), about: new FormControl(this.competi ...

Guide on transforming a Unix timestamp into either "2000-01-01" or "2000-05-24 20:00:00" format, or the opposite way, using Deno

Just starting out with Deno and looking to convert a Unix timestamp such as 1646245390158 into either the format of 2000-01-01 or 2000-05-24 20:00:00, or vice versa. Any tips on how to achieve this? ...

Using React as a monorepo with yarn workspaces, typescript, and leveraging absolute imports

Struggling to configure a React project using yarn workspaces and typescript, with the following folder structure: -root -package.json -workspaces -web -common Here is the content of my package.json file: { "name": "my-project-name", "private" ...

Using Angular's mergeMap feature to concatenate multiple HTTP calls sequentially

The method called getDetails() retrieves an array of Details[]. Within this array, there is a property named name which I need to pass to another HTTP request. Details { name: String; Details getDetails() return this.https.get("/someValue&q ...

Image with responsive div buttons

I am trying to add a set of buttons on each image in my masonry image gallery, but I'm facing issues with responsiveness. Whenever I resize the screen, some of the buttons disappear instead of adjusting their size and position accordingly. I want th ...

I encountered a problem while integrating antd and moment.js in my React project

I am currently using the antd date-picker in my React project with TypeScript. Encountered an error: Uncaught Type Error: moment is not a function. If anyone has a solution, please assist me. .tsx file:: const dateFormat = 'MM-DD-YYYY'; < ...

How can I target and focus on a dynamically generated form in Angular 4/Ionic3?

One of the challenges I'm facing is dealing with dynamically created forms on a page. Each row consists of inputs and a button. Is there a way to select/focus on the input by clicking on the entire row (button)? It should be noted that the number of r ...

When attempting to access the .nativeElement of an input using @ViewChild, the result is 'undefined' rather than the expected value

In my angular2 project, I created a form with the following code: import {Component, ElementRef, ViewChild, AfterViewInit} from "angular2/core"; import {Observable} from "rxjs/Rx"; import {ControlGroup, Control, Validators, FormBuilder} from "angular2/com ...

Is the Prisma model not reachable through Prisma Client?

I'm currently attempting to retrieve a specific property of a Prisma model using Prisma Client. The model in question is related to restaurants and includes a reviews property that also corresponds with a separate Review model. schema.prisma file: // ...

Ensuring TypeScript object types are safe by requiring all keys to be within an array of values

When working with Typescript ^3.8, we have an interface defined as follows: interface IEndpoint { method: 'get'|'put'|'post'|'patch'|'delete', path: string } Additionally, there is a constant declared like ...

Display a loading alert using SweetAlert2 that requires no user interaction

Currently, my code looks like this: swal({ title: 'Loading cars from data base', showLoaderOnConfirm: true, preConfirm: () => { return this.carsSvc.getCars().then((cars: ICar[]) => { this.setData(cars); ...

Converting JSON data into an Angular object

I'm struggling to map the JSON data below to an Angular 7 object: [ { "id": "123456", "general": { "number": "123", "name": "my name 1", "description": "My description with <li> html tags ...

What is the best way to ensure a specific row remains at the bottom of an Angular table with Material when sorting?

My data table contains a list of items with a row at the end showing the totals. | name | value1 | value2 | --------------------------- | Emily | 3 | 5 | | Finn | 4 | 6 | | Grace | 1 | 3 | | TOTAL | 8 | 14 | I&apos ...

Iterating over a JSON array using *ngFor

Here is the JSON structure that I have: { "first_name": "Peter", "surname": "Parker", "adresses": { "adress": [{ "info1": "intern", "info2": "bla1" }, { "info1": "extern", "info2": "bla2" }, { "info1": " ...