I'm trying to invoke a function after my $.each()
finishes using a promise. However, when I try the following code I get Uncaught TypeError: $.each(...).promise is not a function
.
$.each(snapshot.val(), function(chat, i){
firebase.database().ref('chats/'+chat+'/msgs').once('value', function(snap){
if (Object.keys(snap.val())[0] != i){
notification = true;
}
});
}).promise().done( function(){ alert("All was done"); } );
I'm relatively new to promises, can anyone let me know how I can fix this please?
so if that function passed to once
is your callback, the following should help you out.
var promises = [];
$.each(snapshot.val(), function(chat, i){
var dfd = $.Deferred();
firebase.database().ref('chats/'+chat+'/msgs').once('value', function(snap){
if (Object.keys(snap.val())[0] != i){
notification = true;
}
dfd.resolve();
});
promises.push(dfd);
})
$.when.apply($, promises).done(function () {
alert("All was done");
});