Programing

두 번째.그러면() 약속은 정의되지 않은 데이터로 호출된다.

c10106 2022. 3. 21. 08:36
반응형

두 번째.그러면() 약속은 정의되지 않은 데이터로 호출된다.

나는 accountManager라는 서비스에서 아래 보이는 약속을 반환하는 기능을 가지고 있다.

이 약속에 대한 .그러자()는 의도한 대로 반응을 발사하고 출력한다.

  signIn(email:String,password:String):Promise<any>{
    return this.http.post('http://localhost:3000/api/signin',JSON.stringify({
      "email": email,
      "password": password
    }),{headers: this.headers})
      .toPromise()
      .then(res => {
      //**This is defined**
        console.log(res);
      })
  }

이 문제는 내가 이 signIn 방법을 사용하는 다른 클래스에 있을 때 발생한다.약속 내부의 반응은 이제 무효다.함수 자체에서 약속을 생략하면 반환된 약속의 .그러면()은 반응 값을 갖는다.

if (this.loginForm.valid === true){
  this.accountManager.signIn(this.email,this.password)
    .then(response =>{

    //**This .then has an undefined response when added on to the promise returned from the signIn function.**

      let body = JSON.parse(response._body)

      if (body.payload.success === true){
        this.router.navigate(['/']);
      }else{
        this.signInError = true;
      }
  })
    .catch(error=>{
      this.signInError = true;
    })

약속이 반환되고 있을 때, 그 약속 .그러면()이 왜 가치를 포함하는지 아는 사람이 있는가.나는 무엇이 혼란스러운지 분명히 하고 싶다.고마워 :)

@cartant가 말했듯이, 당신은 그 일이 있은 후 다시 레스를 돌려주지 않고 있다.console.log통화. 약속 콜백에서 반환된 값이 약속을 해결한다.

new Promise(function(resolve) {
    // this is almost equivalent 
    // to returning in promise callbacks
    resolve(3);
})
.then(function(res) {
   console.log(res); // logs 3  
   return 7;
})
.then(function(res) {
   console.log(res); // logs 7
   // no return, implicitly returns undefined
})
.then(function(res) {
   console.log(res); // logs `undefined`
});

반환되는 가치는 그 결과로 생기는 또 다른 약속일 수 있다..then콜백은 다음 사항을 해결하기 위한 약속을 청취할 것이다.

new Promise(function(resolve) {
    // this is almost equivalent 
    // to returning in promise callbacks
    resolve(3);
})
.then(function(res) {
   return Promise.resolve(5);  // can create a Promise which resolves immediately
})
.then(function(res) {
   console.log(res); // logs 5
});

참조URL: https://stackoverflow.com/questions/44491352/second-then-on-promise-is-getting-called-with-data-as-undefined

반응형