Функция углового вызова с обещанием в машинописи - PullRequest
0 голосов
/ 27 сентября 2018

У меня есть 3 функции.И я хочу вызвать другую функцию после завершения функции.В моей первой функции я устанавливаю переменную (студентов) на странице.И вторая функция использует эту переменную.Поэтому я использую обещание.Но я перепробовал много способов.Но я не могу выполнить код с обещанием.Я хочу, чтобы в моем buttonClick мои три функции работали в порядке асинхронности.Я хочу как ниже.Как я могу сделать?

  students: [];
  studentInfoList: [];
  otherList: [];

  buttonClick() {
    const myPromise = new Promise(function (resolve, reject) {
      myFirstOperation();
    });

    myPromise()
      .then(result => {
        mySecondOperation();
      })
      .then(result => {
        myThirdOperation();
      });
  }


  myFirstOperation() {
    this.studentService.getStudents().subscribe(
      result => {
          this.students = result.data;
      });
  }

  mySecondOperation() {
    for (let student of this.students) {
      this.studentInfoList.push({ studenNameSurname=student.Name + student.Surname });
    }
  }

  myThirdOperation() {
    for (let studentInfo of this.studentInfoList) {
      this.otherList.push(this.studentInfoList);
    }
  }

Ответы [ 6 ]

0 голосов
/ 27 сентября 2018

Может быть, вам нужно создать 2 обещания.Попробуйте это

  students: [];
  studentInfoList: [];
  otherList: [];

  buttonClick() {

    const myPromise = new Promise(function (resolve, reject) {
     this.studentService.getStudents().subscribe(
      result => {
          this.students = result.data;
          resolve();
      });
    });

    myPromise()
      .then(result => {
        mySecondOperation();
      });
  }

  mySecondOperation() {

     const my2Promise = new Promise(function (resolve, reject) {
        for (let student of this.students) {
          this.studentInfoList.push({ studenNameSurname=student.Name + student.Surname });
        }
          resolve();
     });

     my2Promise()
      .then(result => {
        myThirdOperation();
      });

  }

  myThirdOperation() {
    for (let studentInfo of this.studentInfoList) {
      this.otherList.push(this.studentInfoList);
    }

}

0 голосов
/ 27 сентября 2018

Я нашел решение.Ответ @KrutiChoksiPatel и @SachinShah очень близок к моему ответу.Но они не будут работать.Потому что в этом ответе нет функции "resol ()", как показано ниже.

 buttonClick() {
    this.myFirstOperation().then(() => {
      this.mySecondOperation(() => {
        this.myThirdOperation();
      });
    });
  }

  myFirstOperation() {
    return new Promise((resolve, reject) => {
      this.studentService.getStudents().subscribe(
        result => {
          this.students = result.data;
          resolve(); //This row is important. Because of not working
        });
    })
  }

  mySecondOperation() {
    return new Promise((resolve, reject) => {
    for (let student of this.students) {
      this.studentInfoList.push({ studenNameSurname=student.Name + student.Surname });
      }
      resolve();  //This row is important. Because of not working
    })
  }

  myThirdOperation() {
    for (let studentInfo of this.studentInfoList) {
      this.otherList.push(this.studentInfoList);
    }
  }
0 голосов
/ 27 сентября 2018
students: [];
studentInfoList: [];
otherList: [];

buttonClick() {
    this.myFirstOperation()
        .then(() => {
            this.mySecondOperation();
            this.myThirdOperation();
        })
}


myFirstOperation() {
    new Promise((resolve, reject) => {
        this.studentService.getStudents().subscribe(
            result => {
                this.students = result.data;
                resolve();
            });
    })

}

mySecondOperation() {
    for (let student of this.students) {
        this.studentInfoList.push({ studenNameSurname=student.Name + student.Surname });
    }
}

myThirdOperation() {
    for (let studentInfo of this.studentInfoList) {
        this.otherList.push(this.studentInfoList);
    }
}
0 голосов
/ 27 сентября 2018

Попробуйте так.

student = [];
studentInfoList = [];
otherList = [];

this.buttonClick().then(() => {
  this.buttonClickResult().then((data) => {        
    this.secondFunction().then(() => {
        this.thiedFunction();
    });
  });
})    

 buttonClick(){    
    return new promise((resolve , reject) => {
     // Do your stuff hear
    })
  }

buttonClickResult(){    
  return new promise((resolve , reject) => {
    this.studentService.getStudents().subscribe((result) => {
        this.student.push(...result.data);
        resolve("pass data hear"); // Pass data if you need.                                                               
    })
  })
}

secondFunction(){    
  return new promise((resolve , reject) => {
    for (let data of this.student) {
        this.studentInfoList.push({ "studenNameSurname" : data.Name + data.Surname });
    }
  })
}

thiedFunction(){
   this.otherList.push(...this.studentInfoList); 
}
0 голосов
/ 27 сентября 2018

mySecondOperation и myThirdOperation не делают ничего асинхронного, поэтому вы можете просто написать

buttonClick() {
    this.studentService.getStudents().subscribe(
          result => {
              this.students = result.data;
              for (let student of this.students) {
                    this.studentInfoList.push({ studenNameSurname=student.Name + student.Surname });
              }
              for (let studentInfo of this.studentInfoList) {
                    this.otherList.push(this.studentInfoList);
              }
          });
}
0 голосов
/ 27 сентября 2018

Вы можете использовать async / await

students: [];
  studentInfoList: [];
  otherList: [];

  async buttonClick() {
        await this.myFirstOperation();
        this.mySecondOperation();
        this.myThirdOperation();
  }


 async myFirstOperation() {
    const result = await this.studentService.getStudents().toPromise();
    this.students = result.data;

  }

  mySecondOperation() {
    for (let student of this.students) {
      this.studentInfoList.push({ studenNAmeSurname=student.Name + student.Surname });
    }
  }

  myThirdOperation() {
    for (let studentInfo of this.studentInfoList) {
      this.otherList.push(studentInfoList);
    }
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...