异步函数不返回值,但是控制台日志()做:如何做?
init()this.datagetPostById()
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/awaitinit()
let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')allPosts.init()
.then( d => console.log(allPosts.getPostById(4)) )// resulting Object correctly logged in consoleallPosts.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()Promiseasync/awaitgetPostById(id).
getPostById(id) ?
编辑:
init()
.then( value => doSomethingWithMy(value) )
let value = await myAsyncFn()
等待只能在 async职能:P
awaitasyncawait
.then()async/await.
BIG阳
随时随地看视频慕课网APP
相关分类