如何使函数按顺序执行

问题描述 投票:0回答:1

我正在使用angular和firebase进行项目,并且面临如何使函数同步工作的问题。所以我的controt.ts看起来像这样:

import { Component, OnInit } from '@angular/core';
import { ContratService } from './contrat.service';
import { FormBuilder, FormGroup, FormArray} from '@angular/forms'

@Component({
  selector: 'app-contrat',
  templateUrl: './contrat.component.html',
  styleUrls: ['./contrat.component.css']
}) 
export class ContratComponent implements OnInit {
  today: number = Date.now();

  contrat: FormGroup;
  constructor(private fb:FormBuilder ,private contratService: ContratService) { }

  ngOnInit() {
    this.contrat=this.fb.group({
      id_Contrat : [''],
      Montant : [''],
      date : [''],
      id_Client : [''],
      id_Freelancer : [''],
      tache : this.fb.array([this.creatTache()])
    })
this.contrat.get('date').setValue(this.today);
  }


creatTache():FormGroup{
  return this.fb.group({
           tacheName: [''],
           paiement:[''],
           delai:['']
  })
}
public get tache(){
  return this.contrat.controls['tache'] as FormArray;
}
addTache(){
this.tache.push(this.creatTache());
}
removeTache(i:number){
  this.tache.removeAt(i);
}
try1(){
  let m=0;
  for(let t of this.contrat.get('tache').value){
    m= +m + +t.paiement;
   }

  this.contrat.get('Montant').setValue(m);
}

 try2(u){
  this.contratService.addContrat(u);
}
 onSubmit(i){
this.try1();
this.try2(i);

}

}

在try1()方法中,我试图设置'Montant'的值并在方法try2()中,我试图将数据发送到firebase

问题是try2()在try1()之前执行

angular typescript
1个回答
0
投票

JavaScript中的所有内容都是异步的。意味着如果一行代码正在等待某件事(例如后端请求),那么它将继续进行下一行代码而不会停顿。

您所能做的就是放任自流。

    try1(){
      return new promise of((return) => {
      let m=0;
      for(let t of this.contrat.get('tache').value){
        m= +m + +t.paiement;
       }

      this.contrat.get('Montant').setValue(m);
      return();
     });
    }

     try2(u){
      this.contratService.addContrat(u);
    }
     onSubmit(i){
    this.try1().then(()=> {
    this.try2(i);
    });
   }
© www.soinside.com 2019 - 2024. All rights reserved.