javascript - Promises Syntax -
i've looked through several promise syntax, i'm not understanding (including ones had examples). of them resolved variable, mine bit more complex, , can't seem running right.
i'm using firebase current user, , want run next lines after user.
here's code:
componentdidmount() { var promise = new promise ((resolve, reject) => { var user = fire.auth().currentuser}; resolve( if(user) { console.log('favorites: requesting favorites'); fire.database().ref('/favourites/' + user.uid).once('value').then(function (snapshot) { var recipes_obj = snapshot.val(); let recipes = []; (let id in recipes_obj) { let recipe = recipes_obj[id]; recipe.id = id; recipes.push(recipe); console.log("recipes: ", recipes) } console.log("recipes outside", recipes); this.setstate({ recipes: recipes }); }.bind(this)); } else { console.log('favorites: no user') } ) }
i've tried this
componentdidmount() { var user = new promise ((resolve, reject) => { resolve(fire.auth().currentuser).then(() => { if(user) { console.log('favorites: requesting favorites'); fire.database().ref('/favourites/' + user.uid).once('value').then(function (snapshot) { var recipes_obj = snapshot.val(); let recipes = []; (let id in recipes_obj) { let recipe = recipes_obj[id]; recipe.id = id; recipes.push(recipe); console.log("recipes: ", recipes) } console.log("recipes outside", recipes); this.setstate({ recipes: recipes }); }.bind(this)); } else { console.log('favorites: no user') } }) })
var user = fire.auth().currentuser
this code not asynchronous. when line executes, have user in var user
. don't need use promise in response getting user - have it.
the time need create new promise object , resolve when have work run asynchronously , have no other promise indicate when work complete.
in code don't return new promise caller. means promise useless. unless hand promise off bit of code operates in response resolution, doesn't situation. in other words, promise not doing here.
the bit of code that's asynchronous in code fetch database:
fire.database().ref('/favourites/' + user.uid).once('value')
once()
returns promise. in code, you're calling then() method on promise more work after result available.
Comments
Post a Comment