I have a method in a class which returns JSON object and then outside the class in a function I create an instance of this class, call one of the methods and expect to read returned JSON values. But what happens is that the variable assigned to the method is called at the very start before method even collects the data resulting in undefined. I tried short circuit (&&) which worked for me before, but not this time. I also tried using hooks instead of let and returning that, which ultimately worked for me but for some reason, it was looping as if I put it in while(1). All the methods were taken from an SQLite tutorial and modified.
function Screen() { const a = new App(); let prodReturned = null; prodReturned = a.getProducts(); return (<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}><Text>text: {prodReturned && JSON.stringify(prodReturned)}</Text></View> );}export default class App extends Component {getProducts() { let products=[]; this.listProduct().then((data) => { products = data; console.log(typeof(data),data,'this returns object type and correct json form') return products; }).catch((err) => { console.log(err); })}listProduct() { return new Promise((resolve) => { const favdrinks = []; this.initDB().then((db) => { db.transaction((tx) => { tx.executeSql('SELECT p.favorites FROM drinks p', []).then(([tx, results]) => { console.log("Query completed"); var len = results.rows.length; for (let i = 0; i < len; i++) { let row = results.rows.item(i); console.log(`Drinks favorited: ${row.favorites}`) const { favorites } = row; favdrinks.push({ favorites }); } console.log(favdrinks); resolve(favdrinks); }); }).then((result) => { this.closeDatabase(db); }).catch((err) => { console.log(err); }); }).catch((err) => { console.log(err); }); });}}
How do I make sure to call the method and assign the return value to a variable once it is prepared to do so?