Asynchronous indexedDB in a class object - javascript

I have written a tiny indexedDB library but dosen't seem to work as expected. So my question is how do i fix or properly reconstruct the code bellow to work as expected with a promise. I'm out of idea.
Although the add and delete method works in terms of successfully adding and deleting item from the database but the delete method won't signal it .then function
class IDB {
constructor(name, version) {
this.name = name;
this.version = version;
this.db = null;
}
open(callback) {
const req = window.indexedDB.open(this.name, this.version);
req.onupgradeneeded = (e) => {
let db = e.target.result;
callback(db);
}
req.onsuccess = (e) => {
this.db = e.target.result;
this.db.onversionchange = () => {
this.db.close();
console.log('Tell user to reload the page');
}
}
req.onerror = (e) => {
let db = e.target.errorCode;
return;
}
}
result(req) {
return new Promise((resolve, reject) => {
if (req) {
req.onsuccess = (e) => {
let res = e.target.result;
if (res) {
resolve(res);
}
};
req.onerror = (e) => {
let err = e.target.errorCode;
if (err) {
reject(err);
}
};
}
})
}
add(store, Items) {
let req;
let tx = this.db.transaction([store], 'readwrite').objectStore(store);
Items.forEach(item => {
req = tx.add(item);
});
return this.result(req);
}
get(store, key) {
let req = this.db.transaction([store], 'readonly')
.objectStore(store).get(key);
return this.result(req);
}
cursor(store) {
let req = this.db.transaction(store).objectStore(store)
.openCursor();
return this.result(req);
}
delete(store, key) {
let req = this.db.transaction([store], 'readwrite')
.objectStore(store).delete(key);
return this.result(req);
}
}
Usage
const employeeData = [
{ id: "00-01", name: "gopal", age: 35, email: "gopal#tutorialspoint.com" },
{ id: "00-02", name: "prasad", age: 32, email: "prasad#tutorialspoint.com" }
];
const idb = new IDB('mydb', 1);
idb.open((db) => {
if (!db.objectStoreNames.contains('user')) {
db.createObjectStore('user', {keyPath: 'id'});
}
});
idb.add('user', employeeData).then(() => alert('Items added')).catch(() => alert('failed'));
But I would prefer the usage with the async/await code
await idb.add('..', ..) // blah blah

Related

How to stop a function called infinitely?

I have this bunch of code which runs infinitely as it can be seen from the terminal img. How can I stop it? Delete function is assigned to a button so I don't know why it runs even though I didn't click that button.
//server.js
app.get("/getMaintenanceTypes",(req,res)=>{
pool.query(`Select * from maintenancetypes`, (err, result) => {
if(!err){
console.log("maintanencetypes", result.rows);
res.status(200).send(result.rows);
}else{
res.status(404).json(err.message)
console.log("maintanencetypes", err.message)
}
})
})
//main.js
const getMainTypes = async () => {
const response = await axios.get(`${serverBaseUrl}/getMaintenanceTypes`);
//console.log("response", response.data);
const response2 = [];
for (var i = 0; i < response.data.length; i++) {
let entry = {
id: null,
title: "",
description: "",
};
entry.id = response.data[i].id;
entry.title = response.data[i].title;
entry.description = response.data[i].description;
response2.push(entry);
//console.log("entry", entry);
}
console.log("RESPONSE2", response2);
return response2;
}
async function deleteAllMainTypes() {
try {
const resp = await axios.delete(
`${serverBaseUrl}/deleteAllMainTypes`
);
} catch (error) {
console.log(error);
}
const maintenanceList = await getMainTypes();
//console.log("main list", maintenanceList);
setMaintenanceList(maintenanceList);
};
const deleteHandler = () => {
deleteAllMainTypes();
}
<Button onClick={deleteHandler} >Delete All</Button>

Nodejs Array is always empty, while it should be filled

const generatePropertyAmenities = async (property) => {
let result = [];
property.amenities.map(async (res, key) => {
/**
* Get the amenities type id, creates it if it doesn't exist
* const type_existed_before: defines if the type already existed
*/
let type_id = null;
const type_existed_before = await strapi
.query("amenities-categories")
.findOne({ name: res.type.trim() });
if (type_existed_before) type_id = type_existed_before.id;
else
type_id = await strapi
.query("amenities-categories")
.create({ name: res.type }).id;
res.items.map(async (amenity) => {
const amenity_exists = await strapi
.query("amenities")
.findOne({ name: amenity.name.trim() });
if (amenity_exists) {
// console.log(amenity_exists)
if (
!type_existed_before ||
(type_existed_before &&
!amenity_exists.amenities_categories.find((x) => x === type_id))
) {
await strapi.query("amenities").update(
{ id: amenity_exists.id },
{
amenities_categories: [
...amenity_exists.amenities_categories,
type_id,
],
}
);
}
result = [...result, amenity_exists.id];
} else {
result = [
...result,
await strapi
.query("amenities")
.create({
name: amenity.name.trim(),
amenities_categories: [type_id],
}).id,
];
}
});
});
console.log(result);
return result;
};
result is always empty, am I missing something here ? I really don't see what I'm doing wrong. I checked everything, amenity_exists.id is correct, everything seems correct but something is not I really need some help here guys
Ok so I managed to make it work, I don't think I can explain why and how exactly it works I may need some explanations from you guys, but here's my fix:
const generatePropertyAmenities = async (property) => {
const getAmenityCategoryId = (item) =>
new Promise(async (resolve, reject) => {
const type_existed_before = await strapi
.query("amenities-categories")
.findOne({ name: item.type.trim() });
if (type_existed_before)
resolve({
type_id: type_existed_before.id,
type_existed_before: false,
});
else
resolve({
type_id: await strapi
.query("amenities-categories")
.create({ name: item.type }).id,
type_existed_before: false,
});
});
const getAmenity = (amenity, type_id, type_existed_before) =>
new Promise(async (resolve, reject) => {
const amenity_exists = await strapi
.query("amenities")
.findOne({ name: amenity.name.trim() });
if (amenity_exists) {
// console.log(amenity_exists)
if (
!type_existed_before ||
(type_existed_before &&
!amenity_exists.amenities_categories.find((x) => x === type_id))
) {
await strapi.query("amenities").update(
{ id: amenity_exists.id },
{
amenities_categories: [
...amenity_exists.amenities_categories,
type_id,
],
}
);
}
resolve(amenity_exists.id);
} else {
resolve(
await strapi.query("amenities").create({
name: amenity.name.trim(),
amenities_categories: [type_id],
}).id
);
}
});
const createArrayOfAmenities = () =>
new Promise(async (resolve, reject) => {
let ret = [];
for (let index = 0; index < property.amenities.length; index++) {
const element = property.amenities[index];
let { type_id, type_existed_before } = await getAmenityCategoryId(
element
);
for (let k = 0; k < element.items.length; k++) {
const amenity = element.items[k];
ret = [
...ret,
await getAmenity(amenity, type_id, type_existed_before),
];
}
}
resolve(ret)
});
return await createArrayOfAmenities();
};
Try
await res.items.map(async ...

JS - StreamSaver downlad does not start

I download data from API in chunks decrypt it and than pass to ReadableStream.
But after last chunk, the file is not downloaded.
I work with axios and StreamSaver.js
Code:
Above in the code I declare:
this.filestream = streamSaver.createWriteStream('sample.jpg');
this.writer = await this.filestream.getWriter();
let readableStream;
readableStream = new ReadableStream({
start(ctrl) {
const nextChunk = async () => {
let fileDataResponse = await that.$api.post(
'endpoint', {
file_id: UUID,
chunk_index: index
}, {
headers: {
...
}
}
);
done =
fileDataResponse.data.length <=
fileDataResponse.data.current_index;
if (fileDataResponse.data.data) {
let data = await that.decryptData(fileDataResponse.data.data);
ctrl.enqueue(data);
}
if (!done) {
index += 1;
nextChunk();
} else {
ctrl.close();
}
};
nextChunk();
}
});
const reader = readableStream.getReader();
const close = () => {
that.writer.close();
};
const pump = () =>
reader.read().then((res) => {
if (!res.done) {
that.writer.write(res.value).then(pump);
} else {
close();
}
});
pump();
Where could be my error here?
Thank you a lot!
Issue was the res.value is not an Int8Array

Javascript for of loop runs only once

I'm fetching data form a API and since I have to collect lots of data, I'm using the setTimeOut function to delay the requests by 3s each. But, when I try to run the code, the for loop only run once and finishes the program.
const fs = require('fs')
const { JSDOM } = require("jsdom")
const { window } = new JSDOM("")
const $ = require("jquery")(window)
const path = require('path')
const fetchArt = require('./utils/fetchArt.js')
const { data } = require('jquery')
const { resolve } = require('path')
let replacer = RegExp(' ', 'g')
let slash = RegExp('/', 'g')
const requestArtSongs = (artist) => {
return $.getJSON("https://www.vagalume.com.br/" + artist + "/index.js").then(
function (data) {
return data.artist.lyrics.item
}
)
}
const map = (lang) => {
switch (lang) {
case 1: return 'pt'
case 2: return 'en'
default: return lang
}
}
const requestMusic = (artist, song) => {
return $.getJSON(
"https://api.vagalume.com.br/search.php"
+ "?art=" + artist
+ "&mus=" + song
+ "&apikey={key}"
).then(function (data) {
return [data.mus[0].text, data.mus[0].lang]
})
}
const makeRequest = (art, songs) => {
songs.forEach((song, i) => {
delay(3000 * (i+1))
.then(() => makeSongRequest(art, song.desc))
})
}
const writeFile = (art, songName, mus) => {
gen = gens[0]
let music = {
artist: art,
song: {
name: songName,
text: mus[0],
lang: map(mus[1])
}
}
if (fs.existsSync(path.join(__dirname, 'Genders', gen, art))) {
fs.writeFile(path.join(__dirname, 'Genders', gen, art, `${songName.replace(slash, '')}.json`),
JSON.stringify(music, null, 4),
(err) => {
if (err) throw err
console.log('Song ' + songName + ' written!')
})
} else {
fs.mkdir(path.join(__dirname, 'Genders', gen, art), { recursive: true }, err => {
if (err) throw err
fs.writeFile(path.join(__dirname, 'Genders', gen, art, `${songName.replace(slash, '')}.json`),
JSON.stringify(music, null, 4),
(err) => {
if (err) throw err
console.log('Song ' + songName + ' written!')
})
})
}
}
const makeSongRequest = (art, songName) => {
requestMusic(art, songName)
.then(mus => {
writeFile(art, songName, mus)
})
}
const delay = t => new Promise (resolve => setTimeout(resolve, t))
const writeSongs = (artist) => {
art = artist.replace(replacer, '-').toLowerCase()
return new Promise(() => {
requestArtSongs(art)
.then((songs) => {
makeRequest(artist, songs)
})
})
}
const main = async () => {
let gens = ['Funk']
for (let gen of gens){
let arts = await fetchArt(gen)
for (let art of arts) {
await writeSongs(art)
}
}
}
main()
On my main function, I'm trying to fetch lyrics from the API. For each gender (in this case, only 'Funk') I get the artists that sing that gender. Then, for each artist I run the writeSongs function that does lots of stuff.
I'm using Node JS to do all the work.

I am trying to resolve the data in map function

Below is my code.I am unable resolve the o/p.How to resolve in async and await.I am trying to get data from other collection and pass it to existing filtered collection
exports.listStatus = async (root, { _id, start, limit }) => {
var user = await db.User.find({ _id: _id })
let list = user[0].savedUsers
var blocked = user[0].blockedUsers
var listAll = list.push(_id)
let listOfStatus = await db.Status.find({ userId: { $in: list }, reportStatus: { $ne: _id }, _id: { $nin: blocked } });
let array;
let leng = listOfStatus.length
let statusCommentsArray
var arrayStatus = [];
listOfStatus.forEach((status, key) => {
let promise = new Promise((resolve, reject) => {
var obj = {}
var statusId = status._id
var listOfLiked = status.like
let likeCount = listOfLiked.length
var sortedList = listOfLiked.sort({ createdDate: -1 })
obj.likeCount = likeCount
db.Comment.find({ statusId: statusId }, (err, statusCommentsList) => {
var statusCommentsCount = statusCommentsList.length
var sortedList = statusCommentsList.sort({ createdDate: -1 })
if (statusCommentsCount >= 3) {
statusCommentsArray = sortedList
}
else {
statusCommentsArray = sortedList.slice(0, 3)
}
obj.statusCommentsCount = statusCommentsCount
obj.statusCommentsArray = statusCommentsArray
arrayStatus.push(obj)
leng--;
if (leng == 0) {
resolve(arrayStatus)
}
})
})
promise.then((response) => {
return Promise.resolve(response)
})
})
}

Categories

Resources