我有一个 es6 类,有一个init()方法负责获取数据,转换它,然后this.data用新转换的数据更新类的属性。到现在为止还挺好。类本身有另一种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 data
        }
      } 
      catch (e) { 
         console.log(e)
      }
  }
  getPostById(id){
     return this.data.find( p => p.id === id )
  }
}  
直截了当,除了我async/await在init()方法中有一个机制。现在,此代码将正常工作:
let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')
allPosts.init()
        .then( d => console.log(allPosts.getPostById(4)) )
// resulting Object correctly logged in console
但它只会打印到控制台中:我如何将其allPosts.getPostById(4)用作return函数?
喜欢:
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) )
   // How can I return the RESULT of allPosts.getPostById( postId ) ???
   return allPosts.getPostById( postId )
}
myFunc()返回一个Promise但不是最终值。我已经阅读了几篇关于这个主题的相关文章,但它们都给出了日志记录的例子,再也没有回来。
这是一个包含两种处理方式的小提琴init(): usingPromise和 using async/await。无论我尝试什么,我都无法使用getPostById(id).
这篇文章的问题是:如何创建一个函数来返回 的值getPostById(id)?
编辑:
很多很好的答案试图解释关于主执行循环的 Promises 是什么。经过大量的视频和其他好的阅读,以下是我现在的理解:
我的函数init()正确返回。然而,在主事件循环中:它返回一个 Promise,然后我的工作是从一个有点并行的循环(不是一个新的真正线程)中捕获这个 Promise 的结果。为了从并行循环中捕获结果,有两种方法:
利用
.then( value => doSomethingWithMy(value) )使用
let value = await myAsyncFn(). 现在这是愚蠢的打嗝:
await 只能在
async函数中使用:p
因此它本身返回一个 Promise,可以使用await它应该嵌入到一个async函数中,它可以与await等等一起使用......
这意味着我们不能真正等待 Promise:相反,我们应该无限期地捕获并行循环:使用.then()or async/await。
谢谢您的帮助 !