Awaiting the outcome of the Typescript map function is non-existent

In order to find the subcategories of an article, I am utilizing a many-to-many relationship with TypeOrm that requires Ids.

However, I encountered an issue where the map function is not properly waiting to push the results into the array.

Below is the code snippet featuring the map function along with the list and corresponding logs:

const subcategories = articleDto.subcategoriesIds.split(',').map(x => +x)
const subcategoriesList = []
    
await subcategories.map(async (subcategoryId) => {
    console.log('start:' + subcategoryId)
    const category = await this.subcategoriesService.getSubcategoryById(subcategoryId);
    console.log('mid:' + subcategoryId)
    await subcategoriesList.push(category);
    console.log('end:' + subcategoryId)
});

console.log('### ' + subcategories);
console.log('### ' + subcategoriesList);

The log output is as follows:

start:2
start:3
### 2,3
### 
mid:2
end:2
mid:3
end:3

I'm puzzled as to why the result is not being awaited. Any assistance on resolving this issue is greatly appreciated.

EDIT: Resolved the issue by incorporating Promise.all within the map function:

const subcategories = articleDto.subcategoriesIds.split(',').map(x => +x);

const subcategoriesList = await Promise.all(subcategories.map((subcategoryId) => {
      return new Promise((resolve => {
        this.subcategoriesService.getSubcategoryById(subcategoryId).then(result => {
          resolve(result);
        });
      }))
    }));

Answer №1

Even though Array prototype methods do not wait for asynchronous operations, you can make them await by refactoring your code.

const subcategories = articleDto.subcategoriesIds.split(',').map(x => +x)
const subcategoriesList = []

for (const subCategoryId of subcategories) {
  console.log('start:' + subcategoryId)
  const category = await this.subcategoriesService.getSubcategoryById(subcategoryId);
  console.log('mid:' + subcategoryId)
  await subcategoriesList.push(category);
  console.log('end:' + subcategoryId);
}

console.log('### ' + subcategories);
console.log('### ' + subcategoriesList);

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

Is it possible for a primitive value to function as a type within Typescript?

Is it possible for a primitive value to be considered as a type in Typescript? For example, is the type below considered valid? If not, how can it be modified to make it valid? export type Status = { completed: false; } ...

Sending multipart/form-data with ajax in PHP returns as null

Recently, I encountered an issue with a form I have. It has the following attributes: method="post" and enctype="multipart/form-data" Every time I submit the form using AJAX $("#openTicketSubmit").click(function(){ var support_ticket_form_data = new ...

A guide to displaying JSON data with Ajax

I am diving into the world of Ajax and feeling a bit puzzled about extracting all values from a specific source. <html> <head> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></sc ...

What could be the reason behind encountering the UnhandledPromiseRejectionWarning error while executing npm build in my serverless application?

I am encountering an issue while attempting to execute npm build on my serverless aws-nodejs-typescript project. I am unsure of how to resolve it. Can someone provide guidance on how to troubleshoot this problem? npm build (node:44390) UnhandledPromiseRej ...

Unable to build an optional Node.js dependency using the Angular compiler

Within my npm library, there exists a code snippet that appears as follows: let _Buffer: typeof Buffer; let _require: NodeRequire; let _readFile: (path: string, callback: (err: (NodeJS.ErrnoException | null), data: Buffer) => void) => void; try { ...

Create a dynamic effect by adding space between two texts on the page

const Button = () => { const options = ['test1', 'test2', 'test3']; return ( <div style={{ position: 'absolute', left: '8px', width: 'auto', flexDirection: 'row' ...

Although npm successfully loads Grunt, the grunt command is unfortunately not recognized

Previously, I successfully used grunt on this computer for other projects about 4 months ago. Recently, I tried to use grunt for a new project. Despite loading grunt globally and locally, when I type in $ grunt -v, it says grunt is not recognized. It seems ...

Is there an equivalent of HtmlSpecialChars in JavaScript?

It seems that finding this is proving more difficult than anticipated, even though it's such a simple concept... Is there an equivalent function in JavaScript to PHP's htmlspecialchars? While it's possible to create your own implementation, ...

access information from a modal in Ionic2

One of the functionalities in my webpage involves a button that triggers the creation of a modal upon being clicked. Now, I am looking to initialize a variable within the modal and then pass it back to the page containing the button once the modal is clos ...

Using Vue.js code on an HTML file is only possible when the necessary CDN is included

Just diving into Vue.js and I've got a header html that doesn't include the cdn link for Vue.js. <nav class="navbar navbar-toggleable-md navbar-inverse"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> ...

Tips for finding and showcasing content from a JSON file in an HTML format

A list of project names is being displayed in the side bar by retrieving them from a JSON result. When a user clicks on any of the listed project names on the side bar, it will show the details of that specific project. Additionally, there is now a search ...

What is the best way to incorporate keyboard shortcuts into carousel operations using jQuery?

The example can be found here. I want to be able to navigate through the images using the left and right arrows on my keyboard. How can I achieve this using jQuery or CSS? This is the structure of the HTML: <div id="slider-code"> <a cla ...

Monitor changes in a dynamic child component using Angular fire and TypeScript only (no HTML)

Currently, I am developing a component using TypeScript and passing inputs to my child component from there. In the parent TypeScript file: this.childComponent = this.viewContainerRef.createComponent(this.data.body).instance; this.childComponent['chi ...

A comprehensive method in JavaScript to determine if a variable is defined

There was a moment when I recall stumbling upon a code snippet that utilized a javascript library, possibly lodash, to perform a comprehensive check for the existence of a certain element. For instance: someLib.isDefined(anObject.aNestedObject.anotherNes ...

Find the difference between the sum of diagonals in a 2D matrix using JavaScript

I'm currently practicing on hackerrank and came across a challenge involving a two-dimensional matrix. Unfortunately, I encountered an error in my code implementation. 11 2 4 4 5 6 10 8 -12 The task at hand is to calculate the sum along the primary ...

An error occurred: Unable to locate the file or assembly 'Interop.iTunesLib, Version=1.13.0.0, Culture=neutral, PublicKeyToken=null'

I've been attempting to connect to iTunes using C# programming language. The process involves creating a dll in C# and running it with TypeScript through the Overwolf API. Here's what I've done so far: Generated a .dll file I utilized the ...

PHP Form encountering error due to JSON decoding following an AJAX request

After extensive research and much confusion, I have finally decided to seek help here. I am able to make my AJAX request post successfully in every format except JSON. I am eager to understand JSON so that I can start using it right away instead of learni ...

Resolving issues with Typescript declarations for React Component

Currently utilizing React 16.4.1 and Typescript 2.9.2, I am attempting to use the reaptcha library from here. The library is imported like so: import * as Reaptcha from 'reaptcha'; Since there are no type definitions provided, building results ...

A guide to displaying JSON information within a data list element (dl)

I am facing an issue while trying to iterate through a multidimensional json data array. Each time I loop through the array, only the last element gets printed. var data = [ [{ "id": "67", "name": "Baby & Toddler Clothing ...

Implementing conditional visibility of divs in HTML using Bootstrap 4 dropdown-menu selection

I am working on a dropdown menu bar with 3 options. When the user changes the selected option, I need to show or hide specific div elements accordingly. Can anyone provide guidance on how to achieve this using jQuery? <link rel="stylesheet" href="htt ...