Bagaimana untuk Mengembalikan Nilai Diselesaikan daripada Fungsi Async Dalam Fungsi Async Lain?

DDD
Lepaskan: 2024-10-18 10:20:04
asal
288 orang telah melayarinya

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 )
  }
}  
Salin selepas log masuk

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 )
}
Salin selepas log masuk

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

Atas ialah kandungan terperinci Bagaimana untuk Mengembalikan Nilai Diselesaikan daripada Fungsi Async Dalam Fungsi Async Lain?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!