'How to await for data with pagination?
I have an api from Airtable that comes as the following from their website:
export async function get_all_transactions(base) {
console.log(`getting all transactions:`);
let all_records = [];
// make this function async
base("Transactions")
.select({
maxRecords: 1000,
view: "Grid view",
})
.eachPage(
function page(records, fetchNextPage) {
records.forEach(function (record) {
// add the promise. Casted to promise since I'm not sure if the external promise will behave normally
console.log(
`adding record. type: ${typeof record}. name ${
record.constructor.name
} is a promise: ${typeof record.then === "function"}`
);
all_records.push({ id: record.id, ...record.fields });
console.log("record added: ", all_records);
});
fetchNextPage();
},
function done(err) {
if (err) {
console.error(err);
return [];
} else {
console.log("done getting all transactions", all_records);
return all_records;
}
}
);
console.log(
`end of function. ${all_records}, len: ${
all_records.length
}, type: ${typeof all_records}. name ${
all_records.constructor.name
} is a promise: ${typeof all_records.then === "function"}`
);
let p = Promise.all(all_records);
}
The output of the console is:
getting records
getting all transactions:
end of function. , len: 0, type: object. name Array is a promise: false
idk what: Promise {<fulfilled>: Array(0)}
got the records []
adding record. type: object. name Record is a promise: false
record added: [{…}]
adding record. type: object. name Record is a promise: false
record added: (2) [{…}, {…}]
adding record. type: object. name Record is a promise: false
record added: (3) [{…}, {…}, {…}]
done getting all transactions (3) [{…}, {…}, {…}]
I want to call this function get_all_transactions asynchronously and eventually get an array of data back.
I don't know where to put .then() in this case with pagination in a custom API because I don't know where to assume promises might be. A similar question only called the first page and not every page that might come from the DB.
I don't know why that is returned but the all_records at the end of the program is empty, but inside the function done() it shows all the data inside the array all_records. Why can the program not await for everything to finish and return from done()
Any suggestions or tips would be appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
