array return value is always empty - javascript

i'm trying to program a prototype right now, however i have a problem, my return values, my output overall always returns an empty array.
If I put everything into a function it works, but if I divide everything into code blocks it doesn't work anymore.
I always get an empty array back as I said.
What am I doing wrong?
async function dataLength(){
return new Promise((resolve, reject) => {
pdo.query(`SELECT * FROM mainsites`, function(err, result) {
let results = result;
let resultsLength = results.length;
let dataIndexMainId = [];
for(let index = 0; index < resultsLength; index++){
dataIndexMainId[index] = results[index]["id"];
}
resolve();
})
})
}
async function getSubSitesIndex(length){
let dataSitesIndex = [];
for(let i = 0; i <= length; i++){
await new Promise((resolve) => {
pdo.query("SELECT * FROM subsites WHERE main = ?",[i] , function(err, result) {
dataSitesIndex[i] = result;
resolve();
})
})
}
let filterDataSitesIndex = dataSitesIndex.filter(String);
console.log(filterDataSitesIndex);
return filterDataSitesIndex;
}
async function getIndex(paramIndex){
let indexResult = await paramIndex;
let indexArray = [];
for (let indexRes of indexResult){
for(let res of indexRes){
indexArray.push(res);
}
}
return indexArray;
}
if I execute the code like this
getIndex(
await getSubSitesIndex(
await dataLength()
)
);

In dataLength, your pdo.query call is not properly promisified.
However, you shouldn't have to write 3 functions for this at all. Do not make multiple queries to your database. Use a single query that does a JOIN - much more efficient!
function getIndex() {
return new Promise((resolve, reject) => {
pdo.query(`
SELECT mainsites.id AS main_id, subsites.id AS sub_id
FROM mainsites
JOIN subsites ON subsites.main = mainsites.id;
`, [], (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}

Related

iterating Javascript array and delete based on condition

I want to iterate through an array of words, look up the definition and delete the word if no definition is found.
my code looks as follows;
var words = ["word1", "word2", "word3",]
function Meaning(words){
const getMeaning = async () => {
const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${words}`)
const myJson = await response.json()
for(i = 0; i < words.length; ++i) {
if(!response[i]){
myJson.splice(i,1)
console.log(myJson)
}
}}
This is not really doing anything atm. Where am I going wrong?
edit to add context
tried like this as well;
for(i = 0; i < words.length; ++i)
fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${words[i]}`).then((response) => {
if (response === 404) {
let response = words
words[i].splice(i,1)
console.log(response)
}
throw new Error('Something went wrong');
})
.then((responseJson) => {
let response = words
response[i].splice(i,1)
})
.catch((error) => {
console.log(error)
});
I can print out the 404 error when it finds no definition, but I can't remove it from the words array
After quick look at the API, and it appears to handle only single words, so the caller needs to make the requests one at a time. Here's how to do it...
const baseUrl = 'https://api.dictionaryapi.dev/api/v2/entries/en/';
// one word lookup. resolve to an array of definitions
async function lookupWord(word) {
const res = await fetch(baseUrl + word);
return res.json();
}
// resolve to a bool, true if the word is in the corpus
async function spellCheck(word) {
const defArray = await lookupWord(word);
return Array.isArray(defArray) && defArray.length > 0;
}
// create a spellCheck promise for every word and resolve with the results
// note, this mutates the array and resolves to undefined
async function spellCheckWords(array) {
const checks = await Promise.all(array.map(spellCheck));
for (let i=array.length-1; i>=0; i--) {
if (!checks[i]) array.splice(i,1);
}
}
// test it (a little)
let array = ['hello', 'whereforeartthou', 'coffee'];
spellCheckWords(array).then(() => {
console.log(array)
})
try this code, you need to check every single element of array from response
var words = ["word1", "word2", "word3"];
function Meaning(words) {
const getMeaning = async () => {
const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${words}`)
const myJson = await response.json()
let result = [];
myJson.forEach(element => {
if(words.includes(element)) {
result.push(element)
}
});
return result;
}
return getMeaning();
}

Promise All & await Async function return always promise pending

I am currently programming object oriented. I had programmed a project as a prototype, it works wonderfully now. I would now like to chop it up one by one.
I always get Promise Pending, what am I doing wrong?
exports.orderArticles = async (data) => {
let indices = [];
await Promise.all([data]).then((results) => {
let dataIndex = results;
for(let results of dataIndex){
for(let res of results){
indices.push(res);
}
}
});
console.log(indices)
return indices;
}
Try like this
exports.orderArticles = async (data) => {
let indices = [];
const results = await Promise.all([data])
for(let result of results){
for(let res of result){
indices.push(res);
}
}
}
console.log(indices)
return indices;
}

Trying to get the function to return the arr with the pushed data in it, but for some reason its not returning it there

Here I have required the sql in my main index file
seeded the database and checked that the sql query returns
// require sql connection from main index
const connection = require('./index');
async function tow() {
let arr = [];
let one = await connection.query("Select name FROM department", (err, res) => {
if (err) throw err;
// console.log(res);
console.log('1'arr);
for (let i = 0; i < res.length; i++) {
// pushing to the array here
arr.push(res[i].name);
}
console.log('2',arr);
});
console.log('3',arr);
return one;
}
// I want this function to return array with the pushed elements
tow();
You need to return arr. Also you are mixing the promise style with the callback style of async, you can do either one, but not a mix. Try something like this.
If connection.query returns a promise:
async function tow() {
let arr = [];
let one = await connection.query("Select name FROM department").then(res => {
// console.log(res);
console.log('1', arr);
for (let i = 0; i < res.length; i++) {
// pushing to the array here
arr.push(res[i].name);
}
console.log('2',arr);
return arr; // need to return arr
},
err => console.error(err));
console.log('3',arr);
return one;
}
tow().then(res => console.log('result', res));
In your case, where connection.query expects a callback function, you can convert the callback to a promise like this.
function tow() {
return new Promise((resolve, reject) => {
let arr = [];
connection.query("Select name FROM department", (err, res) => {
if (err) reject();
// console.log(res);
console.log('1', arr);
for (let i = 0; i < res.length; i++) {
// pushing to the array here
arr.push(res[i].name);
}
console.log('2',arr);
resolve(arr);
});
})
}
// I want this function to return array with the pushed elements
tow().then(res => console.log('result', res));
Here's a codeSandbox

Var has same value after using await in function running using Promise.all

In a function run1 random value is generated & stored in random_var, await is used to delay and then random_value is resolved.
When running run1 asynchronously using Promise.all the random_var is changed when logging after await statement as shown in the code snippet demo
main()
async function main() {
await Promise.all([run1(), run1(), run1()]).then(value => {
console.log({ values: value })
})
}
async function run1() {
return new Promise(async (resolve, reject) => {
random_var = makeid(6)
console.log('Logging 1st time has different values', random_var)
await new Promise(resolve => setTimeout(resolve, 500))
console.log('Logging 2nd time has same values', random_var)
resolve(random_var)
})
}
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
This has to do with hoisting and scope.
You line random_var = makeid(6) doesn't use let or const so it gets hoisted to the global scope where it will not change when the promises resolve.
changing it to const random_var = makeid(6) (or let or var, but best practice is const here because you're not going to ever mutate it) should resolve the issue.
main()
async function main() {
await Promise.all([run1(), run1(), run1()]).then(value => {
console.log({ values: value })
})
}
async function run1() {
return new Promise(async (resolve, reject) => {
const random_var = makeid(6)
console.log('Logging 1st time has different values', random_var)
await new Promise(resolve => setTimeout(resolve, 500))
console.log('Logging 2nd time has same values', random_var)
resolve(random_var)
})
}
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}

loop json call from (previous call) last result value

this call asks from starting name and result limit, the max limit is 1000, so i have to recall it many times with last result value of previous call to collect all results.
steem.api.lookupAccounts(lowerBoundName, limit, function(err, result)
i tried using a set to save the results and then get the last value in the set and recall using it but i started hitting my head to the wall.
here is my tries :
<script src="https://cdn.steemjs.com/lib/latest/steem.min.js"></script>
<script>
steem.api.lookupAccounts('a', '1000', function(err, result) {
//var last = result[999];
//console.log(last);
var mySet = new Set();
mySet.add(result);
var last = mySet.slice(-1)[0];
//var ok = mySet.last();
console.log(last);
var i;
for (i = 0; i < 5; i++) {
steem.api.lookupAccounts(mySet.pop(), '1000', function(err, result) {
});
}
});
// mySet.forEach(function(value) {
// console.log(value);
//});
</script>
let all = [];
let fetchAll = (start = "a") => {
fetchPart(start)
.then((result) => {
all.push(result);
if(result.length == 1000){
fetchAll(result[result.length - 1]);
}
});
}
let fetchPart = (start) => {
return new Promise((ok) => {
steem.api.lookupAccounts(start, '1000', function (err, result) {
console.log(result);
ok(result);
});
});
}
fetchAll();
This might do the trick for you. all will be an array containing all sub results.

Categories

Resources