承诺后jQuery每个

Promise after jQuery each

本文关键字:每个 jQuery 承诺      更新时间:2023-09-26

我试图在$.each()使用promise完成后调用一个函数。但是,当我尝试以下代码时,我得到了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"); } );

我对承诺还比较陌生,有人能告诉我如何解决这个问题吗?

因此,如果传递给once的函数是您的回调,以下内容应该会帮助您。

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");
});

此代码首先执行每个Json,然后执行done函数。

$(Json).each(function (Cont, Item) {
    *//Scrolls through all items iemphasized textn Json.*
    *//Count is Number of Item* 
    *//Item is Item node*
}).promise().done(function(){
   alert("All was done");
});

//.procise()在此链接中输入链接描述

//.done()在此链接中输入链接描述