NodeJs Console.log не выводит результаты - PullRequest
0 голосов
/ 27 ноября 2018

Добрый день,

У меня проблемы с NodeJs / Javascript.Ожидаемое поведение таково: console.log с выводом названия приложений в Google Play Store, которые «прочитали ваши контакты» в разрешениях с использованием следующей библиотеки: https://github.com/facundoolano/google-play-scraper/

Однако мой console.log делаетничего не выводится в конце, кажется, что apps[i].appId пусто как-то.Вот мой код:

gplay = require('google-play-scraper');

gplay.search({
    term: "horoscope",
    num: 40
}).then(function(apps) {

        for (i = 1; i <= apps.length; i++) {

            gplay.permissions({
                appId: apps[i].appId,
                short: true
            }).then(function(perm) {


                    for (a = 1; a <= perm.length; a++) {

                        if (perm[a] == 'read your contacts') {

                            console.log(apps[i].appId)

                        }


                    }


                }


            )
        }

    }
);

1 Ответ

0 голосов
/ 27 ноября 2018

Вы не можете поместить асинхронный вызов в цикл for, как этот.Создайте массив обещаний, а затем используйте Promise.all , чтобы дождаться завершения всех вызовов API.

Я создал работающую программу на основе вашего примера кода.Я добавил пояснения в виде встроенных комментариев:

// use 'const' to define gplay because it doesn't get reassigned
const gplay = require('google-play-scraper');

gplay.search({
    term: "horoscope",
    num: 40
}).then(function(apps) {

    // create an array to collect the calls to get permissions
    // use 'const' to define it because it doesn't get reassigned
    const getPermissions = [];

    // arrays are zero based, start with 0, not with 1
    // use 'let' to define 'i'
    for (let i = 0; i < apps.length; i++) {
        const appId = apps[i].appId;

        // fill the array with Promises, i.e. call objects
        // that get resolved with a result after a while
        getPermissions.push(
            gplay.permissions({
                appId: appId,
                short: true
            }).then(function (perm) {
                // we put our permissions in a result object
                // along with the app ID
                return {
                    appId: appId,
                    perm: perm
                }
            })
        );
    }

    // Wait until all the promises are resolved after the
    // Google Play API was called – we get an array of results
    Promise.all(getPermissions).then(function(results) {
        // iterate through the results array, get a result
        // object for each iteration
        for (let r = 0; r < results.length; r++) {
            const result = results[r];
            const appId = result.appId;
            const perm = result.perm;

            // arrays are zero based, start with 0, not with 1
            // use 'let' to define 'a'
            for (let a = 0; a < perm.length; a++) {
                // always use "===", never use "=="!
                if (perm[a] === 'read your contacts') {
                    console.log(appId)
                }
            }
        }
    })
});

Обратите внимание, что это все еще «код новичка», то есть его можно упростить, используя Array.map , деструктурирование объекта , функции стрелок и т. Д. Я намеренно пропустил это, чтобы было легче понять код.

Более продвинутая версия кода:

const gplay = require('google-play-scraper');

gplay.search({
    term: "horoscope",
    num: 40
}).then(apps => {

    const getPermissions = apps.map(app => {
        const { appId } = app;
        return gplay.permissions({
            appId,
            short: true
        }).then(perm => ({
            appId,
            perm
        }))
    });

    Promise.all(getPermissions).then(results =>
        results.forEach(({ appId, perm }) =>
            perm.forEach(p =>
                p === 'read your contacts' && console.log(appId)
            )
        )
    )
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...