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

Embarking on a new undertaking with Visual Studio 2015 and diving into the world of Angular

My journey to getting Angular2 working in Visual Studio 2015 Pro involved a lot of trial and error, but I eventually found a setup that worked for me. Despite the abundance of instructions out there, I struggled to find clear answers tailored specifically ...

Angular 4 allows you to assign unique colors to each row index in an HTML table

My goal is to dynamically change the colors of selected rows every time a button outside the table is clicked. I am currently utilizing the latest version of Angular. While I am familiar with setting row colors using CSS, I am uncertain about how to manip ...

Change MongoDB data to JSON format on the client's end

I am currently working on converting data from MongoDB that is passed via cookies on my client side from the server. I am utilizing Express and React.js for this task. Client Side: export default class Profile extends React.Component { constructor(){ ...

Encountering Angular error when trying to assign an undefined array to another array while using mock data

Attempting to conduct unit testing on a component involving the retrieval of 'Groups' data through a data resolver class. Below is the corresponding code: export class GroupsComponent implements OnInit, OnDestroy { group: IGroup; groups: IGro ...

Omit functions from category

This question reminds me of another question I came across, but it's not quite the same and I'm still struggling to figure it out. Basically, I need to duplicate a data structure but remove all the methods from it. interface XYZ { x: number; ...

Deriving types from object combinations

Can the Foo type be 'flattened' to return { A?: string; B? number } in the code snippet below? type Foo = { A: string } | { B: number } type Flatten< T, Keys extends keyof T = T extends any ? keyof T : never, > = { [K in Keys]?: T[K] } ...

Passing a service into a promise in Angular 2 using TypeScript

Is there a way to pass a service into a promise? I am currently working on a promise that will only resolve once all the http requests are complete. However, I am facing an issue where this.jiraService is undefined. Is there a method to pass it to the co ...

Typescript encounters a failure in typing when an object is destructured

There is a function that returns an object with two properties (res, mes) where one of them could be null: const fetchJSON = <Res, Body>(link: string, body: Body): Promise<{ res: Res; mes: null } | { res: null; mes: Popup }> => { return n ...

Ensure there is a gap between each object when they are arranged in a

Is there a way to customize the layout of elements in the ratings view so that there is automatic spacing between them? I considered using text (white spaces) for this purpose, but it seems like an inefficient solution. Are there any other alternatives to ...

Apollo-Server presents errors in a polished manner

It seems like the question explains itself adequately. I am currently using 'apollo-server-core' version 3.6.5 Desired Errors: { "errors": [ { "message": "Syntax Error: Unexpected < ...

What is the most effective method for designing a scalable menu?

What is the most effective way to create a menu similar to the examples in the attached photos? I attempted to achieve this using the following code: const [firstParentActive, setFirstParentActive] = useState(false) // my approach was to use useState for ...

Tips for implementing server-side pagination with MongoDB and Node.js

Currently, I am tackling a project that involves handling a significant volume of data. Querying all this data at once from mongodb is not feasible as it would lead to a poor user experience. In order to address this issue, I am in the process of setting ...

Combining Firebase analytics with an Ionic 3 application using the Ionic Native plugin

I placed the GoogleService-Info.plist file at the root of the app folder, not in the platforms/ios/ directory. When I tried to build the app in Xcode, an error occurred in the following file: FirebaseAnalyticsPlugin.m: [FIROptions defaultOptions].deepLin ...

Is Typescript familiar with the import -> require syntax, but unfamiliar with the require -> import syntax?

My code includes a simple file that utilizes the ES6 module loader: 1.ts import {foo} from "./2" foo('hello'); 2.ts function foo (a){console.log(a);}; export {foo} When the tsconfig is configured as follows: "module": "commonjs", We can o ...

Locate MongoDB documentation pertaining to arrays of objects with two specific fields

For instance, consider a Mongo db collection: [ { "user_id": 1, "lead_id": 901, ... ... }, { "user_id": 2, "lead_id": 902, ... ... }, { "user_id": 2, & ...

I am searching for a way to retrieve the event type of a svelte on:input event in TypeScript, but unfortunately, I am unable to locate it

In my Svelte input field, I have the following code: <input {type} {placeholder} on:input={(e) => emitChange(e)} class="pl-2 w-full h-full bg-sand border border-midnight dark:bg-midnight" /> This input triggers the fo ...

What is the functionality of the node class within a doubly linked list?

Within the Node class, the next property can only be assigned a value of type Node or null. class Node { value: any; next: Node | null; prev: Node | null; constructor(value: any) { this.value = value; this.next = null; this.prev = null ...

How can you alter the background color of a Material UI select component when it is selected?

I am attempting to modify the background color of a select element from material ui when it is selected. To help illustrate, I have provided an image that displays how it looks when not selected and selected: Select Currently, there is a large gray backgr ...

Having trouble with VSCode/tsconfig path configurations, as the files are being fetched but still receiving a "Module not found" error in the editor

Since I began working on this project, I've been encountering a peculiar issue. When importing modules and files in my Angular components/classes using import, I face an error in VSCode when the paths use the base path symbol @. Strangely enough, desp ...

How come I am receiving the E11000 error from Mongo when I have not designated any field as unique?

Encountering an issue while attempting to save the second document to MongoDB Atlas. The error message reads as follows: Error:MongoError: E11000 duplicate key error collection: test.orders index: orderId_1 dup key: { orderId: null } Despite having no un ...