비동기 함수에서 값을 반환하는 방법은 무엇입니까?
제공된 코드에서 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() 값을 올바르게 반환합니다.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3