【问题标题】:Loop over pages when requesting API请求 API 时循环页面
【发布时间】:2019-10-16 11:50:38
【问题描述】:

我请求一个 API,我必须使用 start_page 和 count 属性遍历不同的“页面”(近 5000 个“页面”)。我想将获取的数据存储到 mySQL 数据库中。 如何循环遍历“页面”并将数据同步存储到数据库中? 我是一个使用 promises 和其他异步技术的新手。

感谢您的帮助!

循环看起来像:

for (var i = Math.floor(body.pagination.total_result / body.pagination.items_per_page); i >= 0; i--) {
    listOfPromises.push(
        new Promise(function(resolve, reject) {
            request(schedulesURL + 'start_page=' + i + '&count=' + _COUNT, { json: true }, function(err, response, body) {
                if (err) { 
                    console.log('Erreur et i = ' + i);
                    reject(err);
                } else { 
                    //On résoud la promesse :
                    resolve(data);
                }
            })
        }));
    }

我创建了一个这样的递归函数:

// Recursive function
function handlePromises(promises, cb, data = {
    dataSchedules: new Array(),
    dataExceptions: new Array()
}) {
    // If there is no more promises
    // break the function
    if (promises.length == 0) {
        cb(data);
    } else {
        // Shift remove the first elemn in array
        // and remove it from the array
        let promise = promises.shift()
        promise.then((promiseData) => {
            // do what you want with data
            return handlePromises(promises, cb, data)
        }).catch(function(err) {
            console.error(err);
        });
    }
}

【问题讨论】:

  • 您能否提供一个minimal reproducible example 并简要介绍一下您到目前为止所做的尝试?
  • 你能提供一个关于你尝试过的东西吗?

标签: javascript node.js


【解决方案1】:

这是我认为你需要的:

async function init() {
    for (var i = Math.floor(body.pagination.total_result / body.pagination.items_per_page); i >= 0; i--) {

        await new Promise((resolve, reject) => {
            request(schedulesURL + 'start_page=' + i + '&count=' + _COUNT, { json: true }, function(err, response, body) {
                if (err) {
                    console.log('Erreur et i = ' + i);
                    reject(err);
                } else {
                    //On résoud la promesse :
                    resolve(data);
                }
        })
    });
}


init();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2023-03-16
    • 2021-07-27
    • 1970-01-01
    相关资源
    最近更新 更多