异步函数不返回值,但是控制台日志()做:如何做?
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()
Promise
async/await
getPostById(id)
.
getPostById(id)
?
编辑:
init()
.then( value => doSomethingWithMy(value) )
let value = await myAsyncFn()
等待只能在 async
职能:P
await
async
await
.then()
async/await
.
相关分类