How to pass a full object into a promisse assync await in javascript

Viewed 69

Im just trying to sort this with no luck how to understand this async await promisse

this method will be used to call a dialog material before the update operation. The dialog has a subscribe and this is the reason I`m using this async await here.

this is the code:

  async execute(task: ITask): Promise<boolean> {
    return new Promise((resolve) => {
      this.confirmation
        .confirmDelete(`${task.id} - ${task.title}`)
        .subscribe(async (confirmed) => {
          if (confirmed) {
            await this.repository.update(**<Task[]**>(task.id));
            this.dialogService
              .openConfirmDialog('Are you really want to delete/update/create?')
              .afterClosed();
          }
          resolve(confirmed);
        });
    });
  }
}

How to pass a object there in <Task[]>

I apreciate your help

Thanks

edited:

this is the task.repository.ts

import { environment } from './../../../environments/environment';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ITask } from '../models/itask';

@Injectable({
  providedIn: 'root',
})
export class TaskRepository {
  constructor(private httpClient: HttpClient) {}

  create(task: ITask): Promise<ITask> {
    return this.httpClient
      .post<ITask>(`${environment.api}/tasks`, task)
      .toPromise();
  }

  update(entity: ITask): Promise<ITask> {
    const { id, ...data } = entity;
    return this.httpClient
      .put<ITask>(`${environment.api}/tasks/${id}`, data)
      .toPromise();
  }

  getById(id: string): Promise<ITask> {
    return this.httpClient
      .get<ITask>(`${environment.api}/tasks/${id}`)
      .toPromise();
  }

  getAll(): Promise<ITask[]> {
    return this.httpClient
      .get<ITask[]>(`${environment.api}/tasks/`)
      .toPromise();
  }

  async delete(id: string): Promise<void> {
    await this.httpClient.delete(`${environment.api}/tasks/${id}`).toPromise();
    return;
  }
}

Updated 2

using task as a parameter, solve the problem, but here at my .ts component start to complaim

import { ITask } from './../../models/itask';
import { GetTaskHandler } from './../../business-rules/get-task.handler';
import { UpdateTaskHandler } from './../../business-rules/update-task.handler';
import { CreateTaskHandler } from './../../business-rules/create-task.handler';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';


@Component({
  selector: 'app-task-form-page',
  templateUrl: './task-form-page.component.html',
  styleUrls: ['./task-form-page.component.scss'],
})
export class TaskFormPageComponent implements OnInit {
  pageTitle = 'Nova tarefa';

  // configuração do formulário
  form = this.formBuild.group({
    title: [''],
    description: [''],
    done: [false],
  });

  get title(): FormControl {
    return this.form.get('title') as FormControl;
  }
  get description(): FormControl {
    return this.form.get('description') as FormControl;
  }
  get done(): FormControl {
    return this.form.get('done') as FormControl;
  }

  taskId: string | undefined = undefined;

  constructor(
    private formBuild: FormBuilder,
    private activatedRouter: ActivatedRoute,
    private createTaskHandler: CreateTaskHandler,
    private updateTaskHandler: UpdateTaskHandler,
    private getTaskHandler: GetTaskHandler,

  ) {}

  async ngOnInit(): Promise<void> {
    const paramId = this.activatedRouter.snapshot.paramMap.get('id');
    if (paramId) {
      this.taskId = paramId;
      await this.loadTask();
    }
  }

  async loadTask(): Promise<void> {
    const response = await this.getTaskHandler.execute(this.taskId || '');

    if (response) {
      this.pageTitle = 'Editando tarefa';
      // atualizando o formulário com os valores retornados pela api
      this.form.patchValue({
        title: response.title,
        description: response.description,
        done: response.done,
      });

    }

  }

  async onSubmit(): Promise<void> {
    const taskToSave: ITask = {
      ...this.form.value, // pegando todos os valores do formulário
      id: this.taskId, // atualizando o id caso exista
    };
    let response: ITask | undefined;


    if (taskToSave.id) {
      ***response*** = await this.updateTaskHandler.execute(taskToSave);
    } else {
      response = await this.createTaskHandler.execute(taskToSave);
    }

    if (response) {
      this.taskId = response.id;
    }
  }
}
2 Answers

You should use await this.repository.update(task);.

I think you made an error, update expects ITask object, so await this.repository.update(**<Task[]**>(task.id)); should be await this.repository.update(task); also I don't think it's a good idea to use a subscription inside a promise. so can you try something like this

 async execute(task: ITask): Promise<boolean> {
    
    // Convert to promise
    const confirmed = await this.confirmation
        .confirmDelete(`${task.id} - ${task.title}`).pipe(first()).toPromise();

    if (confirmed) {
       await this.repository.update(task);
       this.dialogService.openConfirmDialog('Are you really want to delete/update/create?')
              .afterClosed();
    }

    return new Promise((resolve) => {
          resolve(confirmed);
        });
    });
  }
}
Related