JSFiddle - React, Tailwind, and code Playground
Babel + JSX
class Posts {
constructor(url) {
this.ready = false
this.data = {}
this.url = url
}
async init() {
// using Promise
return new Promise((resolve, reject) => {
fetch( this.url )
.then( res => {
res.json().then( data => {
this.data = data
this.ready = true
resolve(data)
})
}, err => {
reject(err)
})
})
/* // using async/await
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( post => post.id === id )
}
}
let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')
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()