"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 다른 비동기 함수 내의 비동기 함수에서 확인된 값을 반환하는 방법은 무엇입니까?

다른 비동기 함수 내의 비동기 함수에서 확인된 값을 반환하는 방법은 무엇입니까?

2024-11-06에 게시됨
검색:854

How to Return a Resolved Value from an Async Function Within Another Async Function?

비동기 함수에서 값을 반환하는 방법은 무엇입니까?

제공된 코드에서 init() 메서드는 Promise를 반환하지만 getPostById() 메소드가 Promise에서 반환된 값에 직접 액세스하려고 합니다. 이 문제를 해결하려면 Promise가 해결된 후 getPostById() 값을 반환하도록 init() 메서드를 수정해야 합니다.

업데이트된 코드는 다음과 같습니다.

class Posts {
  constructor(url) {
    this.ready = false
    this.data = {}
    this.url = url
  }
  async init() {
      try { 
        let res = await fetch( this.url )
        if (res.ok) {
            let data = await res.json()

          // Do bunch of transformation stuff here

          this.data = data
          this.ready = true
          return this.getPostById(4)  // Return the value of getPostById()
        }
      } 
      catch (e) { 
         console.log(e)
      }
  }
  getPostById(id){
     return this.data.find( p => p.id === id )
  }
}  

이제 myFunc 함수는 다음과 같이 작성할 수 있습니다.

let myFunc = async () => {
   const postId = 4
   await allPosts.init()  // I need to wait for this to finish before returning

   // This is logging correct value
   console.log( 'logging: '   JSON.stringify(allPosts.getPostById( postId ), null, 4) )

   // Return the RESULT of allPosts.getPostById( postId ) ???
   return await allPosts.getPostById( postId )
}

이 코드는 getPostById() 값을 올바르게 반환합니다.

릴리스 선언문 이 글은 1729216637에서 재인쇄되었습니다. 침해 내용이 있는 경우, [email protected]으로 연락하여 삭제하시기 바랍니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3