B
B
ban_machine_228_eng2021-02-02 18:23:37
In contact with
ban_machine_228_eng, 2021-02-02 18:23:37

How to do something after the loop ends?

The API of the social network VKontakte allows you to get only 100 posts with one request, which does not suit me.

const resource = await resolveResource({
        api: vk.api,
        resource: context.$match[1],
    });
    const allPosts = [];
    context.reply(`Начинаю сбор информации...`);

    const counter = await vk.api.wall.get({
        // Получаем кол-во постов.
        owner_id: resource.id,
        count: 1,
    });

    for (let i = 0; i < counter.count; i += 100) {
        vk.api.wall
            .get({
                owner_id: resource.id,
                count: 100, // Больше 100 получить нельзя.
            })
            .then((res) => {
                allPosts.push(res); // Пушим пачки постов.
            });
    }

The following code pushes a bunch of posts into an array. The problem is that with a large number of posts, these requests take a very long time to complete. When I try to display this array, it's empty. This is understandable, because the code is synchronous and the log is executed faster than it is possible to return the data of at least one post. Asynchrony is my Achilles heel, and then there is the cycle. I will be glad for any help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Cheremkhin, 2021-02-02
@ban_machine_228_eng

Code for simple case:

const promises = [];
for (let i = 0; i < counter.count; i += 100) {
        promises.push(vk.api.wall
            .get({
                owner_id: resource.id,
                count: 100, // Больше 100 получить нельзя.
            })
    })
}
Promise.all(promises)
 .then(res => res.flat())
 .then (res =>{
   //res === пачки постов.
   // здесь можно что то сделать с постами
})

The API of the social network VKontakte allows you to get only 100 posts with one request, which does not suit me.

Do you think you are the smartest?
If this does not suit VKontakte, you will not receive all the posts at once, you will simply be blocked.
Most likely, you will need to: enter a delay between requests of 100 pieces or use different IP addresses or different accounts, or maybe all together. Gotta get laid...)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question