What is the best way to incorporate a Promise into this function?

Looking to convert this Typescript method into one that returns a Promise, but only once the

this.user.currentCourseId = student.currentCourseId;
line has been executed.

Is it feasible to achieve this?

public getUserData()
{
    ...

    this.authState.auth.getToken().then(token =>
    {
        this.user.token = token;

        this.userService.update(this.user).then(student =>
        {
            this.user.currentCourseId = student.currentCourseId;
        });
    });
}

Answer №1

It's important to note, as highlighted by jfriend, that you cannot delay returning a promise until it is complete. This would be like getting ahead of yourself. Instead, return the promise immediately and then chain off of it to wait for its fulfillment.

Additionally, I'd like to emphasize the usefulness of promise chaining in order to steer clear of falling into the trap known as the "tower of doom":

public fetchUserData()
{
    ...

    // return promise from function
    return this.authState.auth.getAccess().then(token =>
    {
        this.user.token = token;

        // return another promise here to continue the chain
        return this.userService.update(this.user)
    }).then(student => {
        this.user.currentCourseId = student.currentCourseId;
    });;
}

fetchUserData().then(() => {
    // currentCourseId has now been updated
});

Answer №2

By immediately returning the promise, any subsequent promises inside the initial .then() handler are chained to the original promise:

public fetchUserData()
{
    ...

    // return promise from function
    return this.authService.getCurrentUser().then(token =>
    {
        this.user.token = token;

        // additional promise returned here to continue chaining
        return this.dataService.updateUser(this.user).then(student =>
        {
            this.user.currentCourseId = student.currentCourseId;
        });
    });
}

// implementation
fetchUserData().then(() => {
    // access values set within promises
});

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

Formik: Customizing form rendering based on sibling form values

<ParentComponent> ... <Formik initialValues={getInitialValues(data)} enableReinitialize={true} validationSchema={schema} isInitialValid={!isNew} onSubmit={() => {}} render={formikProps => ( <SimulatorForm&g ...

Converting HTML to an array using Angular

Is there a way to convert HTML into an array of entities? For example: 'hi <em>there</em>' => ['hi', '<em>', 'there', '</em>'] ...

Intellisense capabilities within the Gruntfile.js

Is it a feasible option to enable intellisense functionality within a Gruntfile? Given that 'grunt' is not defined globally but serves as a parameter in the Gruntfile, VSCode may interpret it as an unspecified function parameter 'any'. ...

Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh. Below is the code snippet I am currently ...

What steps can I take to resolve this state bug in React?

Looking to create a react application where pressing enter on a block adds a new block below it, pushing the existing blocks down. However, encountering an issue where pressing enter on one block causes a later block to disappear. Seeking guidance on iden ...

Tips for obtaining a customizable environmental variable document in an angular production build

The constants service I have maintains all the necessary constants for the application, such as the base URL of the backend. export class ConstantsService { public BACKEND_URL = 'http://10.0.27.176:8000/'; } This setup is not very flexible be ...

Tips for importing a library in a TypeScript file that expands a JavaScript prototype

After following the instructions provided in this question, I am experimenting with integrating Moment.js to enhance the capabilities of the Date prototype within a TypeScript project. The process of extending the Date prototype appears successful, as out ...

Is there a way to apply a single mongoose hook to multiple methods in TypeScript?

Referencing the response on How to register same mongoose hook for multiple methods? const hooks = [ 'find', 'findOne', 'update' ]; UserSchema.pre( hooks, function( next ) { // stuff } The provided code functions well wi ...

Getting environment variable from JSON file within Angular 4 - a step-by-step guide

I have a file named "appsettings.json" which contains configurations for a specific purpose. I want to include variables from both "environment.ts" and "environment.prod.ts" in this file and access them within the environment files. When I attempt to impo ...

What factors contribute to TypeScript having varying generic function inference behaviors between arrow functions and regular functions?

Consider the TypeScript example below: function test<T = unknown>(options: { a: (c: T) => void, b: () => T }) {} test({ a: (c) => { c }, // c is number b: () => 123 }) test({ b: () => 123, a: (c) => { retur ...

Unable to locate the control specified by the path: 'files -> 0 -> postId'

I am in the process of creating a dynamic form with formArray and running into an issue. When I click on the AddItem button, it should create an input field for uploading files. Here is the HTML code snippet I am using: <div class="row m-auto col-md-1 ...

Creating dynamic HTML in Angular 2 can be achieved by utilizing directives, data

I am interested in building an accordion feature in angular2 without needing to duplicate the structure each time it is used. Similar to how we can create plugins in jQuery and include HTML code, I would like to find a way to achieve this in Angular2. Ca ...

I am attempting to code a program but it keeps displaying errors

What is hierarchical inheritance in AngularJS? I have been attempting to implement it, but I keep encountering errors. import {SecondcomponentComponent} from './secondcomponent/secondcomponent.Component'; import {thirdcomponentcomponent} from & ...

The 'state' property is not found on the 'FetchPeriod' type

Currently, I am embarking on a journey to grasp ReactJS by following a tutorial provided at this Tutorial. Being a novice in the programming language, I find myself at a loss as to what steps to take next. One roadblock I encountered was when attempting ...

Guidelines for locating multiple entries by an array of ids in mongoose

This is the code I have written: const query = await Users.findOne({_id: userId}, 'groups'); const arrayOfGroups = []; // The query.groups variable is an array of strings that contains IDs await Promise.all([query.groups.forEach(async function ...

Utilize Typescript to Invoke Functions of Different Components in Angular 2

Hello everyone, I am a newcomer to Angular 2 and I'm looking to utilize the value of one component in another component. This will help me populate data based on that particular value. In my setup, I have three Components - App.Component, Category.Co ...

Tips for sorting through and minimizing data based on the most recent date

info = { start: 1, data: [ { name: 'Maria', date: '2020-02-15 }, { name: 'Paula', date: '2020-06-10 }, { name: 'Eva', date: '2020-12-05 }, { name: 'Sophia', date ...

Uncharted Territory: Exploring asynchronous loops with async await and Promise.race?

Currently, I am involved in a project that requires brute forcing a PDF password. To achieve this task, I am using PDF.js to verify the password and implementing promise.race to execute parallel functions for efficient performance. This is how I have str ...

Creating hierarchical TreeNode structure in TypeScript

As I work with a flat one-dimensional array of type TreeNode (view interface definition below), my goal is to recursively traverse the array and add subsequent array elements as children. While attempting a non-recursive approach using a buffer, I encount ...

Dynamic data manipulation with Angular ReactiveForms

One of the challenges I am facing involves using formArray for my list of products. Specifically, I am trying to access the value of product_code in my .ts file similar to [ngModel] so that I can manipulate the data accordingly. Can anyone provide guidance ...