2017-03-26 48 views
1

我刚刚读完Clean Code,并试图重构我的Angular 2代码,以便我的每个函数都做一件事情,就像它在该书中说的那样,但是我在获取此代码时遇到了麻烦工作,我认为这归结于对一般承诺缺乏了解。 这是我目前的方法的工作版本。Angular 2 Promise and refactoring

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

这是我在那些失败的最新尝试。我相信这个问题与他们何时被召集以及何时完成承诺有关。我上面的工作代码是我理解的,因为在每次承诺之前都没有发生预填充,但是当我尝试将它们分离时,获得正确的功能时我迷路了。如果任何人都可以帮助我,并希望从概念上解释我错过了什么,我会非常感激。

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 [ '密码']) .setValue(userInfo.password); } }

+0

下面的代码“我一直试图把这个单一方法变成”不是你的工作代码示例的一部分。如果你正确地格式化代码,它也会有很大的帮助。 –

回答

2

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

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

最后,如果您在传递给第一个then()的回调中呼叫then(),则存在问题。承诺的目的是为了避免这种回调金字塔,让它们变平。

尽管它是为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]}; 
    }); 
} 
+0

感谢您的帮助,我现在将研究您的博客文章! – user2415458

+0

1为博客文章 –