I’m trying to loop through and display all keys and values from a Replit DB to a Node.js Express webpage (preferably EJS template) but the asynchronous syntax is making this rather difficult.
The furthest I’ve got is with this helpful solution but I just want to be able to push to an array like result[item] = val and then fetch the val in EJS with result.forEach((key) => {result[key]})
This also looks promising but I couldn’t get it to work in my case.
Below are some examples that might help. Essentially, you want to use list to get all the keys in the database. Then for each key, fetch its value and set the results to the result object.
// set up database
const Client = require("@replit/database");
const db = new Client();
// object to store results
const result = {};
// asynchronous example
db.list().then(function(keys) {
// keys is an array of all the keys in the db
for (let i = 0; i < keys.length; i++) {
const key = keys[i]; // to be safe in the asynchronous callback (because of scope, keys[i] should be fine, but this is probably better anyway)
db.get(key).then(function(value) {
result[key] = value;
});
}
});
// synchronous example (this needs to be within an async function though)
const keys = await db.list();
// keys is an array of all the keys in the db
for (let i = 0; i < keys.length; i++) {
result[keys[i]] = await db.get(keys[i]);
}
Well, you’d probably want to do it after the for loop, so you’d likely need an array of Promises and then Promise.all.
db.list().then(function(keys) {
const result = {}, promises = [];
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
promises.push(
db
.get(key)
.then(function(value) {
result[key] = value;
})
);
}
Promise
.all(promises)
.then(function() {
// do something with result object here
});
});
You could put that all in a Promise rather than async function and return the Promise, which allows you to ‘return’ from within the Promise.all callback.
function getAll() {
return new Promise(function(resolve, reject) {
db.list().then(function(keys) {
const result = {}, promises = [];
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
promises.push(
db
.get(key)
.then(function(value) {
result[key] = value;
})
);
}
Promise
.all(promises)
.then(function() {
resolve(result);
})
// always better safe than sorry
.catch(function(err) {
reject(err);
});
});
}
}
Now you should be able to do await getAll in an async function and get the result object with all keys and values returned.