首頁 > web前端 > js教程 > 主體

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

DDD
發布: 2024-10-18 10:20:04
原創
286 人瀏覽過

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

How to return a value from an async function?

In the provided code, the init() method returns a Promise, but the getPostById() method is trying to access the value returned by the Promise directly. To resolve this, the init() method needs to be modified to return the value of getPostById() after the Promise is resolved.

Here is the updated code:

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 )
  }
}  
登入後複製

Now, the myFunc function can be written as follows:

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 )
}
登入後複製

This code will correctly return the value of getPostById().

以上是如何從另一個非同步函數中的非同步函數返回解析值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!