问题
Lately I've been stuck with a problem that I don't know how to solve. I asked this question and after some efforts we've found that Firebase works differently with promises than normal requests, and I couldn't use them properly.
As explained in the question, I'm filling an array with some informations from Firebase, and I need to call another method when I'm sure the array is filled, in other words when I'm sure the call to Firebase has finished.
This is my code as I'm using it now:
var user_pref = firebase.database().ref('/users/'+ self.api.email_id+'/preferenze/');
var ref = firebase.database().ref('/tag/')
var userTags = [];
var self1 = self;
user_pref.once('value', function(preferenze) {
preferenze.forEach(function(t) {
ref.once('value', function(tags) {
tags.forEach(function(t1) {
if (t.key == t1.key) {
console.log("Found " + t1.key)
userTags.push(t1.key)
}
return false;
});
})
return false;
});
}).then(a =>{
await this.sleep(1000) //----> WORKAROUND
console.log("Out")
this.myTags = userTags
this.findPoiByTag(this.myTags) //method I have to call when finished
})
I'm using this orrible workaround with sleep to be sure the code outside is executed after the one inside. Without that, it prints "Out" before and then all the "Found" in the loop. I've tried using it with promises in every way, but it still doesn't work. Having a look at the docs here I couldn't find anything that would help me.
回答1:
That's indeed pretty bad.
This should be closer to what you need:
var userTags = [];
var self1 = self;
user_pref.once('value', function(preferenze) {
var promises = [];
preferenze.forEach(function(t) {
promises.push(ref.child(t.key).once('value'));
});
Promise.all(promises).then(function(snapshots) {
snapshots.forEach(function(snapshot) {
if (snapshot.exists()) {
userTags.push(snapshot.key);
}
});
})
this.myTags = userTags
this.findPoiByTag(this.myTags) //method I have to call when finished
});
What this does differently:
- It loads each preference key with a direct look (removing the need for a deeply nested loop that was loading way too much data).
- It puts all load of the categories into an array of promises.
- It then calls your function after all promises have resolved.
来源:https://stackoverflow.com/questions/47795594/javascript-how-to-use-promises-in-firebase