Angular 2承诺和重构

时间:2017-03-26 13:41:23

标签: angular angular-promise

我刚读完清洁代码,并且我正在尝试重构我的Angular 2代码,以便我的每个函数都做一件事,就像它在那本书中说的那样,但是我遇到了麻烦工作,我认为这归结为对一般承诺缺乏了解。 这是我目前工作的方法版本。

telnet: connect to address 128.XXX.XXX.27: Operation timed out

我一直试图将这种方法变成

    prepopulateUserInfoFromStorage() {
    var emailFromStorage;
    var passwordFromStorage;

    this._storage.ready().then(() => {
      this._storage.get('email').then((emailValue) => {
        emailFromStorage = emailValue;
      }).then(() => {
        this._storage.get('password').then((passwordValue) => {
          passwordFromStorage = passwordValue;

        })
      }).then(() => {
        if (emailFromStorage != null && passwordFromStorage != null) {

          (<FormControl>this.loginForm.controls['email']).setValue(emailFromStorage);
          (<FormControl>this.loginForm.controls['password']).setValue(passwordFromStorage);
        }
      });
    }).catch(function (error) {
    });
}

这是我对失败者的最新尝试。我认为这个问题与他们何时被召唤以及何时完成承诺有关。上面我的工作代码我理解,因为在每个承诺之后都没有发生预先填充,但是当我试图将它们分开时,我迷失了获得正确的功能。如果有人能在这里帮助我,并希望从概念上解释我所缺少的东西,我会非常感激。

var userInfo = this.getUserInfoFromStorage();
prepopulateUserInfo(userInfo);

(this.loginForm.controls [&#39;密码&#39;])           .setValue(userInfo.password);         }       }

1 个答案:

答案 0 :(得分:2)

首先需要了解异步。您无法直接从异步方法返回信息。你只能回复一个承诺。

其次,您可以使用Promise.all()将两个承诺合并为一个。

最后,如果您在传递给第一个then()的回调中调用then(),则会出现问题。 Promise旨在通过允许扁平化来避免这种回调金字塔。

虽然它是为AngularJS承诺编写的,但我建议你阅读this blog article I wrote,它解释了你陷入的几个陷阱。

prepopulateUserInfoFromStorage() {
    this.getUserInfoFromStorage().then(info => this.prepopulateUserInfo(info));
}

prepopulateUserInfo(userInfo: any) {
  if (userInfo.email != null && userInfo.password != null) {
     (<FormControl>this.loginForm.controls['email']).setValue(userInfo.email);
     (<FormControl>this.loginForm.controls['password']).setValue(userInfo.password);
  }
}

getUserInfoFromStorage() {
  return this._storage.ready()
    .then(() => Promise.all([this._storage.get('email'), this._storage.get('password')])
    .then(array => {
      return {email: array[0], password: array[1]};
    });
}