Javascript 请求API时循环页面
我请求一个API,我必须使用start_page和count属性在不同的“页面”(近5000个“页面”)上循环。我想将获取的数据存储到mySQL数据库中。 如何循环“页面”并将数据同步存储到数据库中? 我是一个有承诺和其他异步技术的新手 谢谢你的帮助 循环看起来像:Javascript 请求API时循环页面,javascript,node.js,Javascript,Node.js,我请求一个API,我必须使用start_page和count属性在不同的“页面”(近5000个“页面”)上循环。我想将获取的数据存储到mySQL数据库中。 如何循环“页面”并将数据同步存储到数据库中? 我是一个有承诺和其他异步技术的新手 谢谢你的帮助 循环看起来像: for (var i = Math.floor(body.pagination.total_result / body.pagination.items_per_page); i >= 0; i--) { listOf
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);
});
}
}
以下是我认为您需要的:
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();
你能不能提供一个和一点关于你到目前为止所尝试的东西的介绍?你能提供一个关于你所尝试的东西的片段吗?