2017-03-26 1 views
1

방금 ​​방금 코드를 읽는 것을 끝내었고 각기 2 개의 코드를 리팩토링하려고했습니다. 따라서 각 함수는 해당 책에서 할 수있는 것처럼 하나의 작업을 수행하지만이 문제가 발생하는 데 문제가 있습니다. 일하기 위해서는 일반적으로 약속에 대한 이해가 부족한 것 같습니다. 이것이 현재 작동중인 작업 방법입니다. 내가각도 2 약속 및 리팩터링

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

에이 하나의 방법을 설정하는 노력했습니다

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

여기에 실패 것들에 내 최신 시도이다. 나는이 문제가 그들이 부름을 받았을 때와 약속을 끝낼 때와 관련이 있다고 생각한다. 위의 작업 코드는 각 약속 이후에 어느 정도까지 미리 채우기가 일어나지 않기 때문에 이해하지만,이를 나눌 때 올바른 기능을 얻지 못하면서 이해할 수 없습니다. 누구든지 여기에서 나를 도울 수 있다면 잘하면 개념적으로 내가 무엇을 놓치고 있는지 설명해 주시면 고맙겠습니다.

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 개 –