Maison > interface Web > js tutoriel > le corps du texte

Comment renvoyer une valeur résolue à partir d'une fonction asynchrone dans une autre fonction asynchrone ?

DDD
Libérer: 2024-10-18 10:20:04
original
288 Les gens l'ont consulté

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 )
  }
}  
Copier après la connexion

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 )
}
Copier après la connexion

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!