I've written the following lambda function to grab data from an API and drop it into a database. This works fine when the API only returns a single page, however with > 1 page the parseData
before the resolve()
runs, but the "Function finished" log is never triggered. Is this resolve()
not resolving the promise I expect it to?
exports.handler = async (event, context, callback) => {
let db = await initDB(); // External function
await api_get('users')
console.log("Function finished");
db.end()
callback(null)
function api_get(type, page = 1, count = 0, results = []) {
return new Promise(async function(resolve, reject) {
let uri = `https://api.com/v1/${type}`;
request.get(uri '?page=' page, async (error, response, body) => {
const data = JSON.parse(body);
results.push(data.users)
current_count = count data.meta.count
if (current_count < data.meta.total) {
await api_get(type, page 1, current_count, results);
}
else {
await parseData(type, results)
resolve()
}
});
});
}
function parseData(type, data) {
return new Promise(async function(resolve, reject) {
switch (type) {
case 'users':
let users = [].concat(...data)
let sql = ''
for (const user of users) {
sql = sql `INSERT INTO users (user_id) VALUES ('${user_id}');`
}
db.query(sql)
.then( () => {
resolve()
})
break;
}
});
}
};
CodePudding user response:
You are not calling resolve() if this condition is met:
if (current_count < data.meta.total) {
// If execution go in this block, you are never calling "resolve()"
await api_get(type, page 1, current_count, results);
}
else {
await parseData(type, results)
resolve()
}