」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何從另一個非同步函數中的非同步函數返回解析值?

如何從另一個非同步函數中的非同步函數返回解析值?

發佈於2024-11-06
瀏覽:491

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

如何從非同步函數傳回一個值?

在提供的程式碼中,init()方法傳回一個Promise,但getPostById() 方法嘗試直接存取 Promise 傳回的值。為了解決這個問題,需要修改 init() 方法,使其在 Promise 解析後傳回 getPostById() 的值。

更新後的程式碼如下:

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