Exploring the differences: Async await, Promises, and Mapping

When faced with the decision between promises, async awaits, and mapping operators like concatMap, how do you determine which one to use?

Specifically, I am working on a scenario where I need to make an http call to my backend, followed by another http call. The data from the second call relies on values returned by the first call. In this case, would it be more efficient to implement async await, a promise, or make use of concatMap? Furthermore, are there general guidelines for selecting the most appropriate method?

I currently have an implementation using concatMap wherein I dynamically generate child components based on the data retrieved from my getTask http call, ensuring each child component has access to annotationFormats.

this.dashboardService.getAnnotationFormats()
    .pipe(
      concatMap(annotationFormats=> this.dashboardService.getTasks())
    )
    .subscribe(
      (tasks)=>{
          for(let task of tasks){
            const componentFactory=this.CFR.resolveComponentFactory(DashboardItemComponent);
            const componentRef=this.vc.createComponent(componentFactory);
            componentRef.instance.task=task;
            componentRef.instance.annotationFormats=annotationFormats;
            componentRef.instance.compInteraction=this;
            this.taskRef.push(componentRef);
          }
        }
    );

Answer №1

When it comes to handling asynchronous code, both async/await and promises serve the same purpose with slightly different syntax. They are used for executing code once a specific task has been completed.

In the context of Angular development, it is recommended to leverage RxJS instead of traditional promises. RxJS offers a wide range of capabilities beyond simple asynchronous operations, allowing developers to create data streams and manipulate them in diverse ways. Although mastering RxJS and reactive programming may require some effort initially, the potential benefits are extensive once you understand its power.

A useful operator in this scenario would be forkJoin, particularly when dealing with independent requests. By passing a list of resources to forkJoin, you can execute asynchronous tasks concurrently and handle their results efficiently – making it ideal for managing HTTP requests:

forkJoin({
  annotationFormats: this.dashboardService.getAnnotationFormats(),
  tasks: this.dashboardService.getTasks(),
})
.subscribe(
  ({tasks, annotationFormats})=>{
      for(let task of tasks){
        const componentFactory=this.CFR.resolveComponentFactory(DashboardItemComponent);
        const componentRef=this.vc.createComponent(componentFactory);
        componentRef.instance.task=task;
        componentRef.instance.annotationFormats=annotationFormats;
        componentRef.instance.compInteraction=this;
        this.taskRef.push(componentRef);
      }
    }
);

Investing time in understanding RxJS is highly beneficial. If you encounter complexities or uncertainties while using RxJS, it's important to refer to the official documentation or seek information online for guidance. It's crucial not to blindly apply RxJS methods but rather comprehensively grasp their functionalities and workflows.

I trust this information proves helpful. :)

Edit:

For versions of RxJS prior to 6.5, the syntax may vary slightly:

forkJoin(
  this.dashboardService.getTasks(),
  this.dashboardService.getAnnotationFormats()
)
.subscribe(
  ([tasks, annotationFormats])=>{
      for(let task of tasks){
        const componentFactory=this.CFR.resolveComponentFactory(DashboardItemComponent);
        const componentRef=this.vc.createComponent(componentFactory);
        componentRef.instance.task=task;
        componentRef.instance.annotationFormats=annotationFormats;
        componentRef.instance.compInteraction=this;
        this.taskRef.push(componentRef);
      }
    }
);

In this version, resources are passed as arguments rather than an object, and the subscription result will be in array form instead of an object format.

Answer №2

Each serves a unique purpose. async/await is utilized when pausing at a point in your code containing asynchronous operations, while promises detect where asynchronous code is running and triggers callbacks.

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

What methods are most effective for evaluating the properties you send to offspring elements?

Currently, I'm in the process of testing a component using Vue test utils and Jest. I'm curious about the most effective method to verify that the correct values are being passed to child components through their props. Specifically, I want to e ...

Calculate the number of elements shared between two arrays using JavaScript

I am working with two arrays of objects and I need to determine how many different types of cars we have. The first array contains the IDs of all the cars, while the second array contains information about the types of cars. Here is the data: var arr = ...

observing calls made with twilio using javascript

My goal is to track the status of a phone call happening between two people using their phone numbers. Let's say +558512344321 and +558543211234 are currently on a call. As soon as the call begins, I want the browser to display "Call in progress," and ...

Updating state in child components from a different child component in React

How can I update the state of one child component when a button is clicked in another child component, both sharing the same parent component? import React from "react": import A from "..."; import B from "..."; class App extends React.Component { r ...

Angular 6's ngFor directive allows for dynamic rendering of arrays

I'm facing an issue with two sets of code - one works, and the other doesn't. I need to understand why. Not Working: <p *ngFor="let recp of recipes"> <div class="row"> <div class="col-xs-12"> <a href="#" class=" ...

Sending back the requested information in C to the ajax (jquery) CGI

After fetching specific data using C in my jQuery, how can I appropriately transfer the data to C? function Run() { $.ajaxSetup({ cache: false }); var obj = {"method":"pref-get","arguments":{"infos":["sys_info"]}}; alert("Post Json:" + JSO ...

Console displaying a 400 bad request error for an HTTP PUT request

I'm currently in the process of developing a react CRUD application using Strapi as the REST API. Everything is working smoothly with the GET, DELETE, and CREATE requests, but I encounter a 400 bad request error when attempting to make a PUT request. ...

Modifying the font style within an ePub document can affect the page count displayed in a UIWebView

Currently in the development phase of my epubReader app. Utilizing CSS to customize the font style within UIWebView, however encountering a challenge with the fixed font size causing fluctuations in the number of pages when changing the font style. Seeki ...

Tips for creating a smooth transition between background colors within a div

Is there a way to smoothly transition between background colors within a div element? I've been struggling with my code and couldn't find a solution. Any help would be greatly appreciated. Thanks in advance. $(document).ready(function( ...

Tips for showcasing information from a composable to a Vue.js component

Having an issue with Vuejs 3 composables where I am trying to create a single composable for three inputs - email type and text type. I'm unable to display the email typed in the button component template even though I have imported the composable hoo ...

When JQuery Ajax encounters an error

I'm facing an issue with my ajax function after setting the dataType to Json. Below is the code snippet: Ajax script: $('#da').on("change",function() { $.ajax({ url: "callAjaxIndex.php", type: "P ...

Utilizing React JS with Material-UI Autocomplete allows for seamlessly transferring the selected item from the renderInput to the InputProps of the textfield component

Exploring the functionality of the updated version of Autocomplete, my goal is to ensure that when an element is chosen from the dropdown menu, the input format of the text field will be modified to accommodate adding a chip with the selected text. Is the ...

Having difficulty utilizing the sendkeys function in webdriverjs, particularly trying to use F11 to maximize the browser

I am currently experiencing an issue where the below code successfully opens a Chrome browser, but it fails to fullscreen the browser using F11. In the past, I used C# and Selenium which worked fine with this method on Chrome and other browsers. It locates ...

Having trouble installing Popper.js?

I have encountered an issue while attempting to install popper.js in my angular project. ng new <<project>> cd <<project>> npm install popper --save npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules&b ...

Incorporating new element into a Typescript array

I'm currently working on a project using TypeScript and MongoDB where I need to insert an item into an array. registeredUsers.update({ guid: ObjectId(req.cookies._id) }, { $addToSet: { favorites: [comicID] } }); The code snippet prov ...

The art of connecting with Angular 2 router and Components

Here are the elements I have: <app-scrollable-area (scrolledDown)="..." class="scrollable-y"> <router-outlet></router-outlet> </app-scrollable-area> I'm wondering how to communicate this event (scrolledDown) to inside ...

Items added to a form using jQuery will not be submitted when the form is posted

Issues with posting data from dynamically appended options in a form select using jQuery have been noticed. When an appended option is selected and the form is submitted, the value does not get posted (in this case, in an email template). Adding another no ...

Oops! Looks like we've encountered a bit of a snag: HttpClient provider is missing

I am currently facing an issue with my code in Testing.ts file. Below is the code segment from Testing.ts: let injector = ReflectiveInjector.resolveAndCreate([ TestService ]) var myInstance = new myTest(injector.get(TestService)); The TestService.ts ...

Tips for preserving newly add row with the help of jquery and php

Currently, I am attempting to implement a functionality on a Wordpress theme options page that dynamically adds rows using jQuery. Below is the HTML code snippet from the THEME-OPTIONS page <a href="#" title="" class="add-author">Add Author</ ...

Guide to create a React component with passed-in properties

Currently in the process of transitioning a react project from redux to mobx, encountering an issue along the way. Previously, I utilized the container/presenter pattern with redux and the "connect" function: export default connect(mapStateToProps, mapDi ...