Is there a different option instead of relying on promises for asynchronous requests?

Let's consider a scenario where we have a basic front end application (perhaps using Angular) and a back end app. When the front end app performs a get request, in most cases, the Angular repository will initiate an $http.get request which will return a promise (for Angular 1) or an observable that can be converted to a promise (for Angular 2 or 4). The repository then returns this promise and the Angular service would typically look something like this:

repository.makeTheGetCall().then(function (response) {
  // process response
}); 

While this method is usually sufficient, it may not be ideal in certain situations.

1) What if the entire logic of the service relies on this single call? In such cases, we end up nesting the entirety of the service within a .then clause.

2) Another scenario could involve making subsequent requests based on the response of the initial Get request, followed by further requests depending on those responses. This leads to multiple chained then clauses.

Both of these situations are not uncommon and often result in what some may perceive as 'unattractive' code. Are there any alternative practices that can be employed to allow for asynchronous calls without the need to return promises from the repository layer to the service layer?

Your insights would be greatly appreciated. Thank you :)

Answer №1

Utilize async/await for handling promises effectively. This method is a modern alternative to the traditional .then() approach.

Instead of the typical structure:

someServiceMethod() {
  repository.makeTheGetCall().then(function (response) {
    // process response
  }); 
}

You can opt for this cleaner and more organized format:

async someServiceMethod() {
  const response = await repository.makeTheGetCall()
  // process response
}

An added advantage is the avoidance of "callback hell", making the code much more streamlined (#1 in your list).

In cases where a Promise is rejected, errors can be managed within a try/catch block. This centralizes error handling into one location. (#2 in your list):

async someServiceMethod() {
  try {  
    const response = await repository.makeTheGetCall()
    const data = await repository.getDataForResponse(response)
    // process data or perform another async operation
  } catch (err) {
    // handle error
  }
}

For further understanding of how to implement async/await, check out this comprehensive guide.

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

Creating an array of a specific field within a JSON string using the collect() method of objx is a straightforward process

Here is the JSON string I am working with: var data = [{"first":"3","second":"1"},{"first":"5","second":"5"},{"first":"7","second":"1"}]; Currently, I am using the following code - objx(data).collect("first") I am expecting to receive an array like [3 ...

transforming array elements into properties of a React component

My text component contains the code below return ( <FormControl variant="outlined" className={classes.formControl}> <Grid container> <TextField id={props.id} label={props.label} d ...

Node Express for Advanced Routing

I'm currently developing a web application that will handle CRUD operations on an array within a collection. Here is the structure of the collection model: var mongoose = require('mongoose'); var website = require('./website'); ...

Using Sails.js to display JSON data retrieved from an HTTPS request in the view

Just getting the hang of Sails.js, so any help is appreciated. I've used an XML service and successfully converted it to JSON using xml2js var req = https.request(options, function(res) { var xml = ''; res.on('data', fun ...

What is the method for retrieving the name of the currently selected HTML element?

After using jQuery to select certain tags, I am now trying to obtain the name of each tag: $('select, :checkbox, :radio').each(function(){ // ... }); To accomplish this, I have attempted the following code: $('select, :checkbox, :radio ...

An uncaught error occurred in ReactJs while trying to read the property 'map' of an undefined variable within the {Component} component

As I pass my array to the props of the sidebar component and try to access it in my child component... After saving the code and checking the browser, an error message pops up: https://i.stack.imgur.com/6cPY8.png import React, { Component } from 're ...

Editing HTML using the retrieved jQuery html() content

I need to modify some HTML that is stored in a variable. For example: var testhtml = $('.agenda-rename').html(); console.log($('input',testhtml).attr('name')); I also tried the following: console.log($(testhtml).find(' ...

"Exploring the Mini Drawer feature on Material UI brings up a whole new page for the Link

Currently, I am working on a project that involves updating stocks using Material UI. I have implemented a mini drawer from Material UI, but when I click on the menu link, it routes to a new page instead of rendering on the homepage itself. In my App.JS f ...

Organize routes into distinct modules in Angular 6

Currently grappling with routing in my Angular 6 application. Wondering if the structure I have in mind is feasible. Here's what it looks like: The App module contains the main routing with a parent route defining the layout: const routes: Routes = ...

Organizing a NodeJS module - properties and functions

I've been struggling to structure my NodeJS application with modules, and after hours of searching, I haven't found a definitive answer. Let's say I want to create a "user" module for creating new users in my code: var newUser = new User(); ...

Encountering an issue when transferring data between controllers utilizing a demo service

During my journey of learning AngularJS, I decided to create a small app that would allow data to be passed between two controllers using services. Below is the code snippet that showcases how I achieved this: The Controller Code <!DOCTYPE html> &l ...

Tips on avoiding the repetition of jQuery functions in AJAX responses and ensuring the effectiveness of jQuery features

My HTML form initially contains only one <div>. I am using an AJAX function to append more <div> elements dynamically. However, the JavaScript functionality that works on the static content upon page load does not work for the dynamically added ...

Why does my chart.js disappear every time I perform a new render?

Hey there, I'm facing an issue with my code. Let me paste what I have... import React, { memo, useEffect } from 'react'; import Chart from "chart.js"; /* redux-hook */ import { useSelector } from 'react-redux' const lineChart = m ...

can a computed property be delayed in its calculation?

Within the code snippet below, we can see that in the compPropsIsBtnDigitizePolygonDisabled function, it initially checks if the digitizePolygonInteractions variable is initialized. If it is not initialized, an error will be triggered. During execution, w ...

Tips for choosing the desired test to execute with Nightwatch Programmatic API

Currently, I am in the process of developing a web application that enables me to execute Nightwatch tests through a visual interface. At this point, I have successfully been able to run all my tests using a post request from my web app utilizing the Nig ...

Background image that covers the entire screen, div elements that scroll on top of the landing screen initially

As a beginner in the world of coding, I apologize for any simple errors in my attempt. Despite researching this issue, I have not been able to find a precise solution that fits my needs. My goal is to create a full-screen background for the landing page. ...

guide on incorporating Google Maps in a Vue.js application

Can anyone help me with displaying a Google Map using Vue.js? I have provided the code below, but I keep getting an error saying "maps is undefined" even though I have installed all the necessary dependencies for Google Maps. <div id="map"></div& ...

Transforming an Excel document into JSON format: inspection of JSON code structure

Looking to transform Excel data into JSON format, but unsure if the current structure will be ideal for processing with D3.js. Planning to incorporate this JSON file within D3.js for visualization purposes. Here's a snippet of the Excel file: In the ...

Numerous linkages facilitated by node-mongodb-native

Currently, I am working on a function aimed at inserting a document into a MongoDb database using the node-mongodb-native module. The function works perfectly fine, except when multiple documents are inserted back-to-back. To test how my function handles m ...

My Tailwind CSS toggle button disappears in dark mode, why is that happening?

<button aria-label="Toggle Dark Mode" type="button" className="lg:inline-flex lg:w-40 md:w-screen p-3 h-12 w-12 order-2 md:order-3" onClick={() => setTheme(theme === 'dark' ? &ap ...