Angular 2 Promise 和重构

Angular 2 Promise and refactoring

我刚刚读完 Clean Code,我正在尝试重构我的 Angular 2 代码,以便我的每个函数都按照那本书中的说明做一件事,但我无法获得这是可行的,我认为这归结为对一般承诺缺乏理解。 这是该方法的当前工作版本。

    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);

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

getUserInfoFromStorage() {
    var emailFromStorage;
    var passwordFromStorage;

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

    return {email: emailFromStorage, password: passwordFromStorage};
  }

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

(this.loginForm.controls['password']) .setValue(userInfo.password); } }

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

其次,您可以使用 Promise.all().

将两个 promise 合二为一

最后,如果您在传递给第一个 then() 的回调中调用 then(),那就有问题了。 Promises 旨在通过允许展平回调来避免这种回调金字塔。

虽然它是为 AngularJS promises 编写的,但我建议您阅读 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]};
    });
}