如何在angular2中做出同步承诺

时间:2016-10-05 05:38:42

标签: http angular promise synchronous

我正在尝试调用位于服务类中的函数,如果该函数返回数据,则一个布尔变量设置为true。我有2个班级作为bollow:student.ts和service.ts:

// student.ts

    public ngOnInit() {
      this.config.load().then(() => {

      this.service.getRecords().then(
         function () { console.log("success getRecord");
                       this.loading = false; },
         function () { console.log("failed getRecord"); 
                       this.loading = true; });

    });
  }

// service.ts

 public getRecord(id: number): Promise<T> {
            return this.getRecordImpl();

        }

 private getRecordsImpl(): Promise<T[]> {




        let url = this.serviceUrl;

        return this.http.get(url, this.getRequestOptionsWithToken())
            .toPromise()
            .then(res => {
                this.records = this.extractData<T[]>(res);
                for (var i = 0; i < this.records.length; i++) {
                    var record = this.records[i];
                    this.onRecord(record);

                }

                 return this.records;

            })

            .catch(this.handleError);

    }

by now,来自服务的记录返回,但是this.service.getRecords();未定义。我无法使用

  

。然后

用于处理成功和失败操作。 我知道让它同步并不是一个好主意。但是认为异步会导致getRecords变得不确定。处理这个问题的解决方案是什么?我希望它按顺序运行。如果service返回任何记录,则变量初始化为false,否则设置为true。

非常感谢任何帮助和指导。

1 个答案:

答案 0 :(得分:0)

我认为你的方法不正确,让一个承诺同步的重点是什么?如果你真的真的想要这样做,我建议你去挖掘Synchronous programming with es6 generators,但通常工作做得很顺利。

从您的代码中我看到您通过在服务中附加.then()来消费您的Promise。这样你就应该创建一个新的Promise。

private getRecordsImpl(): Promise<T[]> {
let url = this.serviceUrl;
return new Promise((resolve, reject) => {
  this.http.get(url, this.getRequestOptionsWithToken())
    .toPromise()
    .then(res => {
      this.records = this.extractData<T[]>(res);
      for (var i = 0; i < this.records.length; i++) {
        var record = this.records[i];
        this.onRecord(record);

      }
      resolve(this.records);
    })
    .catch(this.handleError);
 })
}

在您的代码中使用:

  this.service.getRecords().then(
     function (records) { console.log("success getRecord");
                   this.loading = false; },
     function (err) { console.log("failed getRecord"); 
                   this.loading = true; });