2

I create a function for became all members of all chats in Telegram user account (but this condition is not important). In function send the list of chats ID. Function apiFunctionForRequestMembersListOfChats via angular.forEach make the request for each chats ID to the server and return list of members of this chat. This list adds to the member's list. And all list of members returns from function to program.

function getAllMembers(chatsID) {
    var members = [];
    angular.forEach(chatsID, function(chatID) {
            apiFunctionForRequestMembersListOfChats(chatID).then(function(chat_members) {
                    angular.forEach(chat_members, function(member) {
                        members.push(member);
                        alert("current members count: " + members.length);
                    })
                };
            }); alert("all members count: " + members.length);
        return members;
    }
}

But Javascript, not waits, when API-function completes and return the empty list of members. I became this alerts:

all members count: 0 current members count: 7 current members count: 42 current members count: 59

How make function wait for all api-requests and return the full list of members?

georgeawg
  • 48,608
  • 13
  • 72
  • 95

1 Answers1

1
function getAllMembers(chatsID) {
    var members = [];
    var promise = [];
    angular.forEach(chatsID, function(chatID) {

            promise.push(new Pormise((resolve,reject)=>{
                apiFunctionForRequestMembersListOfChats(chatID).then(function(chat_members) {
                        angular.forEach(chat_members, function(member) {
                            members.push(member);
                            // alert("current members count: " + members.length);
                        })
                        resolve(member);
                });
            }));
        })

        return $q.all(promise);
    }
}

It should work as required and at the end you will get all the request and at member count in response try console when you call this method you will get more clear. Let me know if you still have any doubts.

Yash Ganatra
  • 468
  • 2
  • 12