It is not always a guarantee that all promises in typescript will be resolved completely

I have a requirement in my code to update the model data

{
"customerCode": "CUS15168",
"customerName": "Adam Jenie",
"customerType": "Cash",
"printPackingSlip": "true",
"contacts": [
    {
        "firstName": "Hunt",
        "lastName": "Barlow",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3abb6adb7a1a2b1afacb483b5acafa2bbeda0acae">[email protected]</a>",
        "deliveryAddress": "805 Division Place, Waumandee, North Carolina, 537",
    },
    {
        "firstName": "Barlow",
        "lastName": "Hunt",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="28405d465c4a495a44475f685e47444950064b4745">[email protected]</a>",
        "deliveryAddress": "805 Division Place, Waumandee, North Carolina, 537",
    }
],
"deliveryAddress": [
    {
        "addressName": "Postal",
        "addressType": "postal address",
        "addressLine1": "plaza street",
        "addressLine2": "broome street",
        "suburb": "Guilford",
        "city": "Oneida",
        "state": "Colorado",
        "postalCode": "3971",
        "country": "Belarus",
        "deliveryInstruction": "test delivery address"
    },
    {
        "addressName": "Physical",
        "addressType": "physical address",
        "addressLine1": "plaza street",
        "addressLine2": "broome street",
        "suburb": "Guilford",
        "city": "Oneida",
        "state": "Colorado",
        "postalCode": "3971",
        "country": "Belarus",
        "deliveryInstruction": "test delivery address"
    }
]
}

To accomplish this, I utilized Promise.all. When testing with Postman, I observed that the customer and contact details need to be added first before updating the delivery addresses. Here's how I implemented it:

public async createCustomer(customer: CustomerDTO): Promise<CustomerDTO> {
    let deliveryAddress = [];
    let contacts = [];

    let customerDto = new CustomerDTO();

    // Code here

    return Promise.all([updatedAddress, updatedContacts]).
        then((results: [Promise<boolean>[], Promise<boolean>[]]) => {
            console.log(results);
            return this.customerRepo.getLastUpdatedCustomer();
        }).
        then((result) => {
            return result;
        }).
        catch(e => {
            console.error(e);
            return e;
        });
}

In customerRepository

// Code for updating delivery address

// Problem description

Answer №1

Make sure to pass the promises directly in a flat array structure.

Read about Promise.all on MDN here

If there are non-promise values within the iterable, they will be ignored but still counted in the resulting promise array value (if the promise is fulfilled)

You can achieve this easily by utilizing the spread operator.

let updatedAddress = deliveryAddress.map(async (address: CustomerDeliveryAddressDto) => {
  return await this.customerRepo.updateDeliveryAddress(address, customerDto, address._id);
});
let updatedContacts = contacts.map(async (contact: CustomerContactsDto) => {
  return await this.customerRepo.createOrUpdateContactList(contact, customerDto, contact._id);
});

// Remember to provide a flat array to Promise.all using the `...` spread operator.
return Promise.all([...updatedAddress, ...updatedContacts]).then(/* ... */

Moreover, as you are already working with async/await, it makes sense to also await the Promise.all function call.

const results = await Promise.all([...updatedAddress, ...updatedContacts]);
console.log(results);
return this.customerRepo.getLastUpdatedCustomer();

Answer №2

You have the option to also nest Promise.all for better code organization

let updatedAddresses = Promise.all(deliveryAddresses.map(async (deliveryAddress: CustomerDeliveryAddressDto) => {
  return await this.customerRepo.updateDeliveryAddress(deliveryAddress, customerData, deliveryAddress._id);
}));

let modifiedContacts = Promise.all(contacts.map(async (contact: CustomerContactsDto) => {
  return await this.customerRepo.createOrUpdateContactList(contact, customerData, contact._id);
}));


return Promise.all([updatedAddresses, modifiedContacts])

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

Set a custom primary key for myself and enforce the exclusion of the default _id field in MongoDB

I have a couple of queries: 1- I need to retrieve data from the database using an ID, but the operation is based on the automatically generated key by MongoDB (e.g. _id). Instead, I want to search based on a field that I created myself like id. To achieve ...

Merging declarations fails to function properly following the release of the npm module

The file core.ts contains the definition of a class called AnyId. In another file named time.ts, more methods are added to the AnyId class. This is achieved by extending the type of AnyId using declaration merging: declare module './core' { in ...

Having trouble retrieving documents from a nested collection in Firebase

I am attempting to retrieve all documents from Firebase that are based on a query. Here is my current firebase structure: https://i.stack.imgur.com/tXrX8.png Even though I have two documents inside the "ListaFavorite" collection, when I check using empty ...

A step-by-step guide on importing stompjs with rollup

My ng2 app with TypeScript utilizes stompjs successfully, but encounters issues when rollup is implemented. The import statement used is: import {Stomp} from "stompjs" However, upon running rollup, the error "EXCEPTION: Stomp is not defined" is thrown. ...

Enigmatic Cartography Classification

In my attempt to construct a specialized Map-like class that maps keys of one type to keys of another, I encountered a challenge. A straightforward approach would be to create a Map<keyof A, keyof B>, but this method does not verify if the member typ ...

Define the data type for the toObject function's return value

Is it possible to define the return type of the toObject method in Mongoose? When working with generics, you can set properties of a Document object returned from a Mongoose query. However, accessing getters and setters on these objects triggers various v ...

Utilize Angular 9 to fetch data from an API using the Get method, map them to a class, and

Seeking to extract information from a test URL and convert the data into a list, I aim to exhibit them in an alert/Loop for testing purposes. The dummy API URL being used is: The returned data follows this structure: {"status":"success","data":[{"id":"1" ...

Having trouble sending a JSON object from Typescript to a Web API endpoint via POST request

When attempting to pass a JSON Object from a TypeScript POST call to a Web API method, I have encountered an issue. Fiddler indicates that the object has been successfully converted into JSON with the Content-Type set as 'application/JSON'. Howev ...

Troubleshooting an Angular application in Intellij using Chrome on a Windows operating system

I've been searching for a long time for a way to debug an Angular app in IntelliJ using Chrome on Windows. So far, I have not been successful in attaching a debugger to Chrome. I have tried launching Chrome with --remote-debugging-port=9222 and numer ...

Passing events from a parent component to dynamically created child components in Angular

UPDATE: I've decided to tackle this issue in a different way by retrieving dynamic child component values in the parent component's save() function, following the accepted answer. I am attempting to create a system where a parent component emits ...

Is it planned to include StencilJS as a development choice in Ionic?

I'm curious about the potential adoption of Stencil JS for developing mobile apps within the Ionic framework. When I mention "an option for developing," I'm referring to frameworks like NativeScript where developers can choose between Angular + ...

Dynamic rows in an Angular 2 Material data table

I'm currently working on dynamically adding rows to an Angular 2 Data Table ( https://material.angular.io/components/table/overview) by utilizing a service called "ListService". This service provides me with the columns ("meta.attributes") to be displ ...

Tips for successfully importing $lib in SvelteKit without encountering any TypeScript errors

Is there a way to import a $lib into my svelte project without encountering typescript errors in vscode? The project is building and running smoothly. import ThemeSwitch from '$lib/ThemeSwitch/ThemeSwitch.svelte'; The error message says "Canno ...

Determine whether there is only one array in the object that contains values

At the moment, I am attempting to examine an array in order to determine if only one of its elements contains data. Consider this sample array: playersByGender = { mens: [], womens: [], other: [] }; Any combination of these elements may contain dat ...

Initiating Angular APP_INITIALIZERThe Angular APP_INITIALIZER

I am a newcomer to Angular and currently utilizing Angular6 for development purposes. I have a specific query regarding my app. Before the app initializes, I need to invoke three services that provide configurations required by the app. Let's refer to ...

Transform a collection of interfaces consisting of key-value pairs into a unified mapped type

I have a set of interfaces that describe key-value pairs: interface Foo { key: "fooKeyType", value: "fooValueType", } interface Bar { key: "barKeyType", value: "barValueType", } interface Baz { key: "bazKeyType", value: "bazValue ...

organizing strings in alphabetical order using TypeScript

My md-collection is set up to display a list of emails like this: <md-collection-item repeat.for="u of user" class="accent-text"> <div class="row"> <di ...

Troubleshooting ion-radio loop error in Ionic 2

I am encountering an issue with the ion-radio component in Ionic 2. The problem is that when the component retrieves data from a service using HTTP and assigns it to the data property within the ngOnInit lifecycle hook, the radio buttons are not able to b ...

Node.js, sigma.js, and the typescript environment do not have a defined window

When attempting to set up a sigma.js project with node.js in TypeScript, I encountered a reference error after starting the node.js server: ts-node index.ts The problem seems to be located within the sigma\utils\index.js file. <nodejsproject& ...

Encountering a Nuxt error where properties of null are being attempted to be read, specifically the 'addEventListener' property. As a result, both the default

Currently, I am utilizing nuxt.js along with vuesax as my UI framework. I made particular adjustments to my default.vue file located in the /layouts directory by incorporating a basic navbar template example from vuesax. Subsequently, I employed @nuxtjs/ ...