首页 > web前端 > js教程 > 正文

如何从另一个异步函数中的异步函数返回解析值?

DDD
发布: 2024-10-18 10:20:04
原创
288 人浏览过

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学习者快速成长!